问题描述
我有此类bgp_route:
I have this class bgp_route:
class bgp_route:
def _init_(self, path):
self.nextHop = None
self.asPath = ''
self.asPathLength = 0
self.routePrefix = None
但是,当我运行以下测试代码时,
However, when I run the following test code;
from bgp_route import bgp_route
testRoute = bgp_route()
testRoute.asPath += 'blah'
print testRoute.asPath
我收到以下错误:
Traceback (most recent call last):
File "testbgpRoute.py", line 6, in <module>
testRoute.asPath += 'blah'
AttributeError: bgp_route instance has no attribute 'asPath'
此错误的原因是什么?
bgp_route的实例化是否应该将属性asPath初始化为空字符串?
What is the cause of this error?Shouldn't the instantiate of bgp_route have initialized the attribute asPath to the empty string?
推荐答案
您拼写了 __ init __
:
def _init_(self, path):
您的两端都需要两个下划线。通过不使用正确的名称,Python永远不会调用它,并且永远不会执行 self.asPath
属性赋值。
You need two underscores on both ends. By not using the correct name, Python never calls it and the self.asPath
attribute assignment is never executed.
注意,该方法需要一个 path
参数。您在构造实例时需要指定该参数。由于您的 __ init __
方法否则忽略该参数,因此您可能希望将其删除:
Note that the method expects a path
argument however; you'll need to specify that argument when constructing your instance. Since your __init__
method otherwise ignores this argument, you probably want to remove it:
class bgp_route:
def __init__(self):
self.nextHop = None
self.asPath = ''
self.asPathLength = 0
self.routePrefix = None
这篇关于初学者python错误-找不到属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!