Inheritance in python, Attribute error -
this question has answer here:
i have started learning python , having hard time how inheritance works in python.
i have created 2 classes, 1 named animal , 1 named dog. dog class inherits animal class. have attributes name, height, sound etc in animal class want use in dog class. setting 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 "{} {} cm tall , {} kilograms , 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 '{} {} cm tall , {} kilograms , says {} owner {}'.format(self.__name, self.__height, self.__weight, self.__sound, self.__owner) def multiple_sounds(self, how_many=none): if how_many 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 when try print attributes using object of dog class, error displayed saying "
*line 73, in tostring return '{} {} cm tall , {} kilograms , says {} owner {}'.format(self.__name, attributeerror: 'dog' object has no attribute '_dog__name'*
can me find problem in code ?
members start double underscore sort of private, not accessible cild classes. should use single underscore. python not use implicit access specifiers c++ or java instead special name convention used: names _
prefix protected , names __
private. python not check don't violate convention, considered bad practice access protected or private methods outside of class. if start name double underscore mangled in special way. __name
becomes _animal__name
when use in animal
class , _dog__name
when use in dog
.
Comments
Post a Comment