Question

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
Was it helpful?

Solution

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

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top