This article goes from https://www.cnblogs.com/zyxstar2003/archive/2011/03/21/1989954.html
1, __init__ is not equivalent to the constructor in C #, when it is executed,
instance has been constructedOut.
1 class A (object): 2 def __init__ (self,name): 3 Self.name=name4 def getName (self):5 return'+self.name
When we execute
1 a=a ('hello')
, it can be understood as
1 a=object. __new__ (A) 2 A.__init__(A,'hello')
That is, the __init__ function is to initialize the object after it has been instantiated.
2, sub-class can be
do not rewrite__init__, when instantiating subclasses,
is automatically called__init__ defined in the superclass
1 classB (A):2 defGetName (self):3 return 'B'+Self.name4 5 if __name__=='__main__':6B=b ('Hello')7 PrintB.getname ()
However, if __init__ is overridden and the subclass is instantiated, the defined __init__ in the superclass are not implicitly called again
1 classC (A):2 def __init__(self):3 Pass4 defGetName (self):5 return 'C'+Self.name6 7 if __name__=='__main__':8C=C ()9 PrintC.getname ()
It will be reported "Attributeerror: ' C ' object has no attribute ' name '" error, so if __init__ is overridden, in order to be able to use or extend the behavior in the superclass, it is best to explicitly call the __init__ method of the Super class
1 classC (A):2 def __init__(self,name):3Super (C,self).__init__(name)4 defGetName (self):5 return 'C'+Self.name6 7 if __name__=='__main__':8C=c ('Hello') 9 PrintC.getname ()
__init__ () method in Python note points