The examples in this article describe the Python class inheritance and subclass instance initialization usage. Share to everyone for your reference. The specific analysis is as follows:
[First reference book original (Chinese-English control)]
__init__ Method Description:
If a base class has a __init__ () method The derived class ' s __init__ () method must explicitly call it to ensure proper in Itialization of the base class part of the instance; For example: "Baseclass.__init__ (self, [args ...])"
As a special contraint on constructors, no value is returned; Doing so would cause a TypeError to being raised at runtime.
If its base class also has __init__ (), it must be explicitly called in __init__ () to ensure that its base class part is properly initialized, for example: "Baseclass.__init__ (self, [args ...])" As a special case of a constructor, it has no value returned, and if a value is returned, an exception TypeError is thrown at run time.
1. When the subclass defines the __init__ method, if the call base class __init__ method is not displayed, Python does not call for you, explaining that the run is OK
Class A (): def __init__ (self): print ' A ' class B (a): def __init__ (self): print ' B ' if __name__== ' __main __ ': b=b () >>> b
2. When the subclass does not define the __init__ method, Python will automatically help you invoke the __init__ method of the first base class, with the first note. That is, when a subclass inherits from more than one base class, only the __init__ method of the first base class is called to:
Class A: def __init__ (self): print ' A ' class B: def __init__ (self): print ' B ' class C (b): def __init __ (self): print ' C ' passclass D1 (a,b,c): passclass D2 (b,a,c): passclass D3 (c,b,a): passif (__ name__== ' __main__ '): print ' D1-------;: ' d1=d1 () print ' D2-------;: ' d2=d2 () print ' d3-------: ' d3=d3 () >>> d1------->:ad2------->:bd3------->:c
3) When the __init__ method is not defined by the base class, when the subclass shows the call to the base class __init__ method, Python goes up and calls the __init__ method of the base class of the base class, essentially the same as 2
Class A: def __init__ (self): print ' A ' class B: def __init__ (self): print ' B ' class C1 (b,a): Passclass C2 (A, B): passclass D1 (C1): def __init__ (self): c1.__init__ (Self) class D2 (C2): def __init_ _ (Self): c2.__init__ (self) if (__name__== ' __main__ '): print ' D1-------;: ' d1=d1 () print ' D2-------: ' d2=d2 () >>> d1------->:bd2------->:a
Hopefully this article will help you with Python programming.