问题
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
I get the following error:
Traceback (most recent call last):
File "testbgpRoute.py", line 6, in <module>
testRoute.asPath += 'blah'
AttributeError: bgp_route instance has no attribute 'asPath'
What is the cause of this error? Shouldn't the instantiate of bgp_route have initialized the attribute asPath to the empty string?
回答1:
You misspelled __init__
:
def _init_(self, path):
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.
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
回答2:
It's called __init__
, with two underscores on both side, like any other python magic method.
And BTW, your constructor expects a path
argument.
来源:https://stackoverflow.com/questions/27646226/beginner-python-error-no-attribute-found