Python - accessing parent attribute from child class method is weird
import random
import sys
import os
class Animal:
__name = ""
__height = 0
__weight = 0
__sound = ""
def __init__(self, name, height, weight, sound):
self.__name = name
self.__height = height
self.__weight = weight
self.__sound = sound
def toString(self):
return "{} is {} cm tall and {} kilograms and say {}".format(self.__name,
self.__height,
self.__weight,
self.__sound)
class Dog(Animal):
__owner = ""
def __init__(self, name, height, weight, sound, owner):
self.__owner = owner
super(Dog, self).__init__(name, height, weight, sound)
def toString(self):
return "{} is {} cm tall and {} kilograms and say {} His owner is {}".format(self.__name,
self.__height,
self.__weight,
self.__sound,
self.__owner)
spot = Dog("Spot", 53, 27, "Ruff", "Derek")
print(spot.toString())
When run, this code prints:
return "{} is {} cm tall and {} kilograms and say {} His owner is {}".format(self.__name,
AttributeError: 'Dog' object has no attribute '_Dog__name'
But when I put the toString method in the Dog class aside more like:
class Dog(Animal):
__owner = ""
def __init__(self, name, height, weight, sound, owner):
self.__owner = owner
super(Dog, self).__init__(name, height, weight, sound)
def toString(self):
return "{} is {} cm tall and {} kilograms and say {} His owner is {}".format(self.__name,
self.__height,
self.__weight,
self.__sound,
self.__owner)
It prints correctly by saying:
The spot is 53 cm high and 27 kilograms and says Ruff
Why is this?
Edit: I only realized that the Animal toString method was printed, not the Dog's toString method.
+3
source to share
2 answers
Do not classify attributes as defaults or as "declarations" and do not use __
-prefixed names unless you understand why you might have to use such names. Also, you don't need toString
; __str__
serves the same purpose and is called automatically as needed.
class Animal:
def __init__(self, name, height, weight, sound):
self.name = name
self.height = height
self.weight = weight
self.sound = sound
def __str__(self):
return "{} is {} cm tall and {} kilograms and say {}".format(self.name,
self.height,
self.weight,
self.sound)
class Dog(Animal):
def __init__(self, name, height, weight, sound, owner):
super(Dog, self).__init__(name, height, weight, sound)
self.owner = owner
def __str__(self):
s = super(Dog, self).__str__()
return "{} His owner is {}".format(s, self.owner)
spot = Dog("Spot", 53, 27, "Ruff", "Derek")
+3
source to share