Python subclass inherits the parent class constructor Description

notes 

Case 1:

        Subclasses should automatically call the parent class method: sub-class does not override __init __ () method, the instance subclasses, will automatically call the parent class __init __ () method.

Case 2:

        Subclass does not need to automatically call the parent class methods: Subclasses override method __init __ () method, the instance subclasses will not automatically call the parent class __init __ () a.

Case three:

        Subclasses override the __init __ () method and call the parent's method: using super Keywords: super (sub-class, self) .__ init __ (parameter 1, parameter 2, ....)


class Son(Father):
  def __init__(self, name):   
    super(Son, self).__init__(name)

If it needs to call in the subclasses of the parent class constructor needs to explicitly construct the parent class, or parent class constructor is not rewritten.

Subclass does not override __init__, instance subclasses automatically call the parent class definition of __init__.

Examples

class Father(object): 
    def __init__(self, name): 
        self.name=name 
        print ( "name: %s" %( self.name) ) 

    def getName(self): 
        return 'Father ' + self.name 


class Son(Father): 
    def getName(self):
        return 'Son '+self.name


if __name__=='__main__': 
    son=Son('runoob') 
    print ( son.getName() )

The output is:

name: runoob
Son runoob

If you rewrite the __init__, instantiable subclass, it will not call the parent __init__ already defined syntax is as follows:

Examples

class Father(object): 
    def __init__(self, name): 
        self.name=name 
        print ( "name: %s" %( self.name) ) 
    
    def getName(self): 
        return 'Father ' + self.name 

class Son(Father): 
    def __init__(self, name): 
        print ( "hi" ) 
        self.name = name d

    ef getName(self): 
        return 'Son '+self.name 

if __name__=='__main__': 
    son=Son('runoob') 
    print ( son.getName() )

The output is:

hi
Son runoob

If you rewrite the __init__, to inherit the parent class constructor, you can use the super keyword:

super(子类,self).__init__(参数1,参数2,....)

There is also a classic wording:

父类名称.__init__(self,参数1,参数2,...)

Examples

class Father(object): 
    def __init__(self, name): 
        self.name=name 
        print ( "name: %s" %( self.name)) 

    def getName(self): 
        return 'Father ' + self.name 

class Son(Father): 
    def __init__(self, name): 
        super(Son, self).__init__(name) 
        print ("hi") 
        self.name = name 

    def getName(self): 
        return 'Son '+self.name 

if __name__=='__main__': 
    son=Son('runoob') 
    print ( son.getName() )

The output is:

name: runoob
hi
Son runoob
Published 136 original articles · won praise 71 · views 160 000 +

Guess you like

Origin blog.csdn.net/u012308586/article/details/105063942