__init__中的UnboundLocalError

时间:2014-04-01 13:14:46

标签: python oop constructor init

我开始研究python并且无法理解,哪里是错误

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

没有ammo这样的变量。您只是传递magazine,这就是magazine行没有问题的原因。试试这个:

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