2014-12-25 35 views
0

我有這個類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初始化爲空字符串嗎?

+1

你需要'__init__'不'_init_'。 –

回答

4

你拼錯__init__

def _init_(self, path): 

您需要強調兩端。通過不使用正確的名稱,Python從不調用它,並且從不執​​行屬性分配。

請注意,該方法需要path參數;您在構建實例時需要指定該參數。由於您__init__方法,否則忽略這個說法,你可能想將其刪除:

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

可能還應該添加對象 –

+0

@PadraicCunningham不知道在這個時刻引入該概念是否有幫助。 –

1

它被稱爲__init__,兩邊都有兩個下劃線,就像任何其他的蟒蛇魔法一樣。

而順便說一句,你的構造函數需要path參數。