Example of how to use a subclass to call a parent function in python:
Preface
This article describes how to call the parent class function of a python subclass. The _ init _ () function in the Python subclass will overwrite the function of the parent class, in some cases, you often need to call the parent class function in the subclass. Let's take a look at the details below:
In the following example ,??? This is where the parent class function needs to be called. Next we will introduce it in detail using the routine.
# -*- 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 ???12 12 def ps1(self): print('I\'m %s,%s' %(self.name,self.score)) Score('Bob','99').ps() Score('Bob','99').ps1()
In Python3.5, there are several Calling methods through reading the information.
The first is the direct method. Use the parent class name for direct calling, as shown in figureparent_class.parent_attribute(self)
, The corresponding routine is the statement:
Student.__init__(self,name)
The second is through the super function, suchsuper(child_class, child_object).parent_attribute(arg)
. The first parameter indicates the start point of the parent class, and the second parameter indicates the class instance (generally use self). When the parameter of the parent class method is only self, the parameter args does not need to be written. In addition, when the class is used internally,child_class
,child_object
It can also be omitted. Corresponding routine:
super(Score,self).__init__(name)
Or:
super().__init__(name)
It can also be used outside the class.super
Function,child_class
,child_object
Two parameters.
Summary
The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.