This article mainly introduces python class inheritance and subclass instance initialization usage. it analyzes the usage skills of Python classes and has some reference value, for more information about python class inheritance and subclass instance initialization, see the examples in this article. Share it with you for your reference. The specific analysis is as follows:
[Reference books (Chinese and English)]
_ Init _ method introduction:
If a base class has an _ init _ () method the derived class's _ init __() method must explicitly call it to ensure proper initialization of the base class part of the instance; for example: "BaseClass. _ init _ (self, [args...])"
As a special contraint on constructors, no value may be returned; doing so will cause a TypeError to be raised at runtime.
If its base class also has _ init _ (), it must be explicitly called in _ init, to ensure proper initialization of its base class; for example: "BaseClass. _ init _ (self, [args...]) "As a special condition of the constructor, it has no value returned. if a value is returned, an exception TypeError will be thrown during runtime.
1. if The _ init _ method is defined in the subclass, if the base class _ init _ method is not displayed, python will not help you call the method.
class A(): def __init__(self): print 'a'class B(A): def __init__(self): print 'b'if __name__=='__main__': b=B()>>> b
2. when the _ init _ method is not defined in the subclass, python will automatically help you call the _ init _ method of the first base class. Note that it is the first. That is, when the subclass inherits from multiple base classes, only the _ init _ method of the first base class will be called:
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 for the base class, if the subclass displays the _ init _ method called for the base class, python searches for and calls the _ init _ method of the base class above 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
I hope this article will help you with Python programming.