Just starting out Python, i\'m a fan of Derek Banas and have been following a tutorial and I\'m stuck with a bit of code.
class Dog(Animal):
__owner = \"
The child class itself doesn't have the attribute, use this instead.
return super(Dog, self).toString() + "His owner is {}".format(self.__owner)
Change your function code
from
def toString(self):
return "{} is {} cm tall and {} kilograms and say {} and the owner is {}".format(
self.__name,
self.__height,
self.__weight,
self.__sound,
self.__owner)
to
def toString(self):
return "{} is {} cm tall and {} kilograms and say {} and the owner is {}".format(
self.get_name(),
self.get_height(),
self.get_weight(),
self.get_sound(),
self.get_owner())
Your Animal
class is using Name Mangling. From documentation -
Since there is a valid use-case for class-private members (namely to avoid name clashes of names with names defined by subclasses), there is limited support for such a mechanism, called name mangling. Any identifier of the form
__spam
(at least two leading underscores, at most one trailing underscore) is textually replaced with_classname__spam
, where classname is the current class name with leading underscore(s) stripped.
(Emphasis mine)
Hence , after your Animal
class got defined any name such as __name
would have changed to _Animal__name
, etc. You would also need to access them alike that in your Dog
class.
But I don't think you actually need to use Name Mangling , you should avoid using the two leading underscores, if you didn't mean for Name Mangling to happen.