Old class to call unbound superclass construction method
Class Olddog: def __init__ (self): print ' I am an old dog! ' Self.__hungry = True def eat (self): if self.__hungry: print ' I eat it! ' Self.__hungry = False else: print ' No thanks! ' Class Oldwolf (Olddog): def __init__ (self): olddog.__init__ (self) print ' isn't only a dog but a wolf! '
Oldwolf class If you do not write a constructor, you will automatically inherit all the properties and methods of the parent class. But if you have a constructor in your class, (Dai Jia tells me that Python does not overload it even in the same class), the subclass overrides the constructor of the parent class, and there is no ' __hungry ' thing. So the old class takes the __init__ of the parent class in the constructor of the subclass, invoking itself as a parameter.
Old_dog = Olddog () old_dog.eat () old_dog.eat () Old_wolf = Oldwolf () old_wolf.eat () old_wolf.eat ()
I am a old dog!
I Eat It!
No thanks!
I am a old dog!
Not only a dog but a wolf!
I Eat It!
No thanks!
Process finished with exit code 0
In the new class, the Super function is used, and the new class is either inherited from object or __mataclass__=type
Class Newdog (object): def __init__ (self): print ' I am a new dog! ' Self.__hungry = True def eat (self): if self.__hungry: print ' I eat it! ' Self.__hungry = False else: print ' No thanks! ' Class Newwolf (Newdog): def __init__ (self): super ("Newdog, Self"). __init__ () print ' Not only a dog but a Wolf! '
The new class with super function to my intuitive feeling is like writing a new class is not the name of the parent class, the book says his advantage is if inherit from more than one class, as long as the super to write once, instead of each of the constructors are written once, when Python has multiple inheritance, Some languages do not allow multiple inheritance.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Python Learning notes-constructors in legacy classes and new class inheritance