我开始学习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

最佳答案

错误在__init__参数中。参数定义中没有ammo
请尝试以下操作:

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

我建议不要修改对象。只需创建一个实例变量,它们就可以做同样的事情,但是代码的可读性要高得多。
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

10-07 21:02