The initialization method of the class in Python is __init__ (), so the initialization method of the parent class and subclass is this, the following article mainly introduces the example of the method of calling the parent class function of the Python neutron class, which is introduced by the example code in very detailed, the needs of friends can refer to.
Objective
This paper mainly introduces the contents of the Python subclass calling the parent class function, and the __init__ () function in the Python neutron class overrides the function of the parent class, in some cases it is necessary to call the parent class function in the subclass. The following words do not say much, come together to see the detailed introduction:
In the following routines,??? is where the parent class function needs to be called, and the following routines are described in detail.
#-*-Coding:utf-8-*-class Student: def __init__ (self,name): self.name=name def PS (self): print (' I Am%s '%self.name) class score (Student): def __init__ (self,name,score): self.score=score ??? def PS1 (self): print (' i\ ' m%s,%s '% (Self.name,self.score)) score (' Bob ', ' P '). PS () score (' Bob ', ' PS1 ').
In Python3.5, the following methods are available for accessing data.
The first is direct method. Called directly with the parent class name, such as parent_class.parent_attribute(self)
, the corresponding routine is the statement:
student.__init__ (Self,name)
The second is through the super function, shaped like super(child_class, child_object).parent_attribute(arg)
. The first parameter represents the beginning of the call to the parent class, and the second parameter represents the class instance (usually self), and the parameter args does not have to be written when the parameter of the parent class method is self-only. In addition, when used inside a class, child_class
child_object
It can also be omitted. corresponding routines:
Super (Score,self). __init__ (name)
Or:
Super (). __INIT__ (name)
Functions can also be used outside the class super
, but there child_class
are child_object
two parameters.
Summarize