문제

I begin to study python and cant understand, where is error

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

error log

self.__dict__["ammo"] = ammo
UnboundLocalError: local variable 'ammo' referenced before assignment
도움이 되었습니까?

해결책

The error is in your __init__ arguments. There's no ammo in the argument definition.

Try the following:

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

I would advice against modifying the objects __dict__. Just create an instance variable, they do the same thing but the code is far more readable.

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

And of course, you should read the official tutorial on classes

다른 팁

There is no such variable as ammo. You are only passing magazine which is why it has no problem with the magazine line. Try this instead:

class Gun(object):
    def __init__(self, magazine=6, ammo=10):
        self.__dict__["magazine"] = magazine
        self.__dict__["ammo"] = ammo
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top