Beginner python error - no attribute found

北慕城南 提交于 2020-01-17 01:23:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!