2014-04-01 52 views
2

我開始學習Python和無法理解,這裏是錯誤UnboundLocalError在__init__

class Gun(object): 
    def __init__(self, magazine=6): 
     self.__dict__["magazine"] = magazine 
     self.__dict__["ammo"] = ammo 

錯誤日誌

self.__dict__["ammo"] = ammo 
UnboundLocalError: local variable 'ammo' referenced before assignment 

回答

4

錯誤在你的__init__的論點。參數定義中沒有ammo

嘗試以下操作:

class Gun(object): 
    def __init__(self, magazine=6, ammo=5): # Now there is! 
     self.__dict__["magazine"] = magazine 
     self.__dict__["ammo"] = ammo 

我會建議對修改的對象__dict__。只需創建一個實例變量,他們做同樣的事情,但代碼更具可讀性。

class Gun(object): 
    def __init__(self, magazine=6, ammo=5): 
     self.magazine = magazine 
     self.ammo = ammo 

In [3]: gun = Gun() 

In [4]: gun.ammo 
Out[4]: 5 

In [5]: gun.magazine 
Out[5]: 6 

當然,你應該閱讀official tutorial on classes

0

有作爲ammo沒有這樣的變量。你只是通過magazine這就是爲什麼它與magazine線沒有問題。試試這個:

class Gun(object): 
    def __init__(self, magazine=6, ammo=10): 
     self.__dict__["magazine"] = magazine 
     self.__dict__["ammo"] = ammo