I am having trouble getting a subclass to behave properly. When instantiating the superclass, everything works as expected. But the getters and setters in the subclass don't seem to do anything.
Commenting out the call to the superclass __init__
function has no effect, its as if its not even there.
class Animal:
__name = None
__sound = 0
def __init__(self, name, sound):
self.__name = name
self.__sound = sound
def set_name(self, name):
self.__name = name
def get_name(self):
return self.__name
def get_sound(self):
return self.__sound
def get_type(self):
return "Animal"
def toString(self):
return "{} says {}".format(self.__name, self.__sound)
class Dog(Animal):
__owner = None
def __init__(self, name, sound, owner):
super().__init__(name, sound)
self.__owner = owner
def set_owner(self, owner):
self.__owner = owner
def get_owner(self):
return self.__owner
def get_type(self):
return "Dog"
def toString(self):
return "{} says {} and his owner is {}".format(self.__name, self.__sound, self.__owner)
cat = Animal('Whiskers', 'Meow')
print(cat.toString())
spot = Dog("Spot", "Borf!", "Derek")
spot.set_name = "Spot?"
spot.set_owner = "Brad"
print(spot.get_type())
print(spot.get_name())
print(spot.get_owner())
print(spot.toString())
print(spot.multiple_sounds(howmany=4))
The given output comes out as:
Whiskers says Meow
Dog
Spot
Derek
Traceback (most recent call last):
File "./hellopython.py", line 245, in <module>
print(spot.toString())
File "./hellopython.py", line 228, in toString
return "{} says {} and his owner is {}".format(self.__name, self.__sound, self.__owner)
AttributeError: 'Dog' object has no attribute '_Dog__name'
Which I don't understand, as I am expecting the name and owner to be changed. Why can't anything be gotten or set outside of the superclass init function? I am using python 3, other posts on this topic have suggested putting arguments in the class to super (python 2 only, tried it and still doesn't work). Why are the attributes not accessible in this context?