I'm a Python newbie, trying to understand the philosophy/logic behind the inheritance methods. Questions ultimately regards why and when one has to use the __init__
method in a subclass. Example:
It seems a subclass inheriting from a superclass need not have its own constructor (__init__
) method. Below, a dog inherits the attributes (name, age) and methods (makenoise) of a mammal. You can even add a method (do_a_trick
) Everything works as it ``should", it seems.
However, if I wanted to add a new attribute in the subclass as I attempt to do in the Cats class, I get an error saying "self" is not defined. Yet I used "self" in the definition of the dog class. What's the nature of the difference?
It seems to define Cats as I wish I need to use __init__(self,name)
and super()__init__(name)
. Why the difference?
class Mammals(object):def __init__(self,name):self.name = nameprint("I am a new-born "+ self.name) self.age = 0def makenoise(self):print(self.name + " says Hello")class Dogs(Mammals):def do_a_trick(self):print(self.name + " can roll over")class Cats(Mammals):self.furry = "True" #results in error `self' is not definedmymammal = Mammals("zebra") #output "I am a new-born zebra"
mymammal.makenoise() #output "zebra says hello"
print(mymmmal.age) #output 0mydog = Dogs("family pet") #output "I am a new-born family pet"
mydog.makenoise() #output "family pet says hello"
print(mydog.age) # output 0
mydog.do_a_trick() #output "family pet can roll over"