初学者python错误 - 找不到属性

时间:2014-12-25 10:11:06

标签: python class attributes

我有这个班级bgp_route:

class bgp_route:
    def _init_(self, path):
        self.nextHop = None
        self.asPath = ''
        self.asPathLength = 0
        self.routePrefix = None

但是,当我运行以下测试代码时;

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初始化为空字符串?

2 个答案:

答案 0 :(得分:4)

你拼错了__init__

def _init_(self, path):

两端都需要两个下划线。通过不使用正确的名称,Python从不调用它,并且永远不会执行self.asPath属性赋值。

请注意,该方法需要path参数;在构造实例时,您需要指定该参数。由于您的__init__方法忽略了此参数,您可能希望将其删除:

class bgp_route:
    def __init__(self):
        self.nextHop = None
        self.asPath = ''
        self.asPathLength = 0
        self.routePrefix = None

答案 1 :(得分:1)

它被称为__init__,两侧都有两个下划线,就像任何其他python魔法一样。

顺便说一下,你的构造函数需要一个path参数。