Вопрос

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