Your code does not work because you are checking that the class Avatar
has the attribute __hp
, which it does not have it, only instances have it, since that attribute is defined in __init__
. In other words, the hasattr
should be called on the self
or avatar
object, not on the Avatar
class.
Moreover, double underscores have a special meaning in python, it mangles the name so that is "private" in the sense that cannot be accessed directly. This means that checking that the instance has the attribute __hp
will not work (you should check _Avatar__hp
instead)
I changed your code to simplify and remove things that do not make too much sense:
class Avatar:
def __init__(self,HP=100):
self._hp = HP
>>> avatar = Avatar()
>>> hasattr(avatar, '_hp')
True
Note: if you create an instance of Avatar avatar = Avatar()
, you should be calling the methods directly on the object avatar.mymethod()
, and not Avatar.mymethod(avatar)