Python subclass inherits the parent class (pass arguments and do not pass arguments)
Class A (object):def __init__(self,a='A'): Print('Enter:', a)Print('Leave:', a) Class B:def __init__(self,a=None):Print('ENter B') Super (b,self).__init__(a)Print '111'b=B ()Print '222'b=b (123) Output:111Enter B ('ENter:', None) ('Leave:', None) Leave B222Enter B ('ENter:', 123)('Leave:', 123) Leave B
When no arguments are found, the output is none, and the a= ' a ' in the parent class A is not used, because the pass parameter of B to A is none
It is important to note that when you inherit a parent class with super () in python2.7, the parent class needs to be in a (object) format, because super is the use of the new class (new class breadth first, classic class depth first)
Solution:
Class A (object):def __init__(self,a='A'): Print('Enter:', a)Print('Leave:', a) Class B (A):def __init__(self,a=None):Print('Enter B') ifA =None:super (b,self).__init__() Else: Super (b,self).__init__(a)Print('Leave B')Print '111'b=B ()Print '222'b=b (123) Output:111Enter B ('ENter:','A')('Leave:','A') Leave B222Enter B ('ENter:', 123)('Leave:', 123) Leave B
(Logic ibid., simple notation):
Class A (object):def __init__(self,a='A'): Print('Enter:', a)Print('Enter:', a) Class B (A):def __init__(self,a=None):Print('Enter B') exec('Super (b,self). __init__'+ (A!=none and '(a)' or '()'))#Actual execution Process#exec (' super (b,self). __init__ '. __add__ (A!=none and ' (a) ' or ' () ')) Print('Leave B')Print '111'b=B ()Print '222'b=b (123) Output:111Enter B ('ENter:','A')('Leave:','A') Leave B222Enter B ('ENter:', 123)('Leave:', 123) Leave B
Solution Two:
Class A (object):def __init__(self,a='A'): Print('Enter:', a)Print('Leave:', a) Class B (A):def __init__(self,*args,**Kwargs):Print('Enter B') Super (b,self).__init__(*args,**Kwargs)Print('Leave B')Print '111'b=B ()Print '222'b=b (123)Print '333'b=b (a=123) Output:111Enter B ('ENter:','A')('Leave:','A') Leave B222Enter B ('ENter:', 123)('Leave:', 123) Leave B333Enter B ('Enter:', 123)('Leave:', 123) Leave B
Simple notation
Class A (object):def __init__(self,a='A'): Print('Enter:', a)Print('Leave:', a) Class B (A):def __init__(self,*args,):Print('Enter B') Super (b,self).__init__(*args)Print('Leave B')Print '111'b=B ()Print '222'b=b (123) Output:111Enter B ('ENter:','A')('Leave:','A') Leave B222Enter B ('ENter:', 123)('Leave:', 123) Leave B
The flaw is that it cannot be passed the dictionary (double pointer), B=B (a=123) is not possible.
Subclass inherits Parent Class argument 01