I am learning Python I hope they are flexible. I want to check whether multiple inheritance worked or not, so I want this class to dog
:
class dog(animal,to_jump):
def __init__(self,name):
self.name = name
print(f"my dog {self.name} is barking and he is {self.var}")
also inherit the method from this:
class to_jump:
#this is a method
def jump(self):
self.var = "jumping"
to check it I want to print what is in the class variable to_jump (self.var)
but in another class, I want it to do this printing correctly.
print(f"my dog {self.name} is barking and he is {self.var}")
and it throws me this error.
File "herencia.py", line 18, in __init__ print(f"my dog {self.name} is barking and he is {self.var}" AttributeError: 'dog' object has no attribute 'var'
this is the instance of the dog class.
instancia = dog("bruno")
It's not a problem of inheritance, it's a problem of where you create the instance attribute.
self.var
is created injump
, it does not exist before itjump
is called , neither in the parent class nor inDog
.If you call the inherited method in the initializer
jump
before trying to use the instance attribute, there is no problem:This is one of the reasons why it's always good practice to initialize all instance attributes in the class initializer: