I have recently started learning python and i am having a hard time how inheritance works in python.
I have created two classes, one is named Animal and another one is named Dog. Dog class inherits Animal class. I have some attributes like name, height, sound etc in Animal class which i want to use in Dog class. I am setting the attributes using init method of Animal class.
class Animal:
__name = ""
__height = 0
__weight = 0
__sound = 0
def __init__(self, name, height, weight, sound):
self.__name = name
self.__height = height
self.__wight = weight
self.__sound = sound
def set_name(self, name):
self.__name = name
def get_name(self):
return self.__name
def set_height(self, height):
self.__height = height
def get_height(self):
return self.__height
def set_weight(self, weight):
self.__weight = weight
def get_weight(self):
return self.__weight
def set_sound(self, sound):
self.__sound = sound
def get_sound(self):
return self.__sound
def get_type(self):
print("Animal")
def tostring(self):
return "{} is {} cm tall and {} kilograms and says {}".format(self.__name,
self.__height,
self.__weight,
self.__sound)
cat = Animal("whiskers", 50, 20, "meow")
print(cat.tostring())
class Dog(Animal):
__owner = None
def __init__(self, name, height, weight, sound, owner):
super(Dog, self).__init__(name, height, weight, sound)
self.__owner = owner
def set_owner(self, owner):
self.__owner = owner
def get_owner(self):
return self.__owner
def get_type(self):
print("dog")
def tostring(self):
return '{} is {} cm tall and {} kilograms and says {} His owner is {}'.format(self.__name,
self.__height,
self.__weight,
self.__sound,
self.__owner)
def multiple_sounds(self, how_many=None):
if how_many is None:
print(self.get_sound())
else:
print(self.get_sound() * how_many)
my_dog = Dog("spot", 50, 40, "Ruff", "Derek")
print(my_dog.tostring())
Problem is when i try to print all the attributes using object of Dog class, an error is displayed saying "
*line 73, in tostring
return '{} is {} cm tall and {} kilograms and says {} His owner is {}'.format(self.__name,
AttributeError: 'Dog' object has no attribute '_Dog__name'*
Can anyone help me find the problem in this code ?