1 Subclass Call Parent Class construction method
classAnimal (object):def __init__(self):Print("Init Animal class~") defRun (self):Print("Animal run!")classDog (Animal):def __init__(self):#The Kawai class does not override the constructor method, and the parent class is called. Otherwise, Python does not automatically call the parent class construction method.
#three ways to explicitly call the parent class construction method #animal.__init__ (self) #Super (Dog, self). __init__ ()Super ().__init__()Print("Init Dog class~") defRun (self):Print("Dog run!")
Test Dog (). Run () The result is as follows
class~class~dog run!
Subclasses implement their own constructors, will call their own constructors, Python does not automatically call the parent class constructor (unlike Java), since it is inherited, spicy should be in the subclass of the constructor to manually call the parent class constructor. There are three ways of doing this.
If you change the dog class to:
class Dog (Animal): def Run (self): Print ("dog run! ")
Here's the default constructor for dog, Test Dog (). Run () The result is as follows
class~dog Run
When a subclass does not define its own constructor, it invokes the constructor of the parent class. What if there are multiple parent classes?
classAnimal (object):def __init__(self):Print("Init Animal class~") defRun (self):Print("Animal run!")classFather (object):def __init__(self):Print("Init Father class~")classDog (animal,father):defRun (self):Print("Dog run!")
Test Dog (). Run () The result is as follows
class~dog run!
Only the animal constructor is run, if father is placed in the first parent class
class Dog (father,animal): def Run (self): Print ("dog run! ")
Test Dog (). Run () The result is as follows
class~dog run!
When a subclass does not define its own constructor, only the constructor of the first parent class is called.
2 Subclass call Parent class common method
class Animal (object): def Run (self): Print ("animal run! " )class Bird (Animal): def Run (self): # Animal.run (self) #super (Bird, self). Run() super (). Run ()
Test Bird (). Run () The result is as follows:
Animal run!
You can find and invoke the constructor method in the same way.
Methods for calling the parent class from the Python neutron class