新聞中心
Python中的子類中的__init__()函數(shù)會(huì)覆蓋父類的函數(shù),一些情況往往需要在子類里調(diào)用父類函數(shù)。

如下例程里,處是需要調(diào)用父類函數(shù)的地方,接下來結(jié)合例程具體介紹。
1 # -*- coding:utf-8 -*-
2 class Student:
3 def __init__(self,name):
4 self.name=name
5 def ps(self):
6 print('I am %s'%self.name)
7
8 class Score(Student):
9 def __init__(self,name,score):
10 self.score=score
11 ???
12 def ps1(self):
13 print('I\'m %s,%s' %(self.name,self.score))
14
15 Score('Bob','99').ps()
16 Score('Bob','99').ps1()
Python3.5中,通過查閱資料,有如下幾種調(diào)用方式。
第一種是直接法。使用父類名稱直接調(diào)用,形如 parent_class.parent_attribute(self),對(duì)應(yīng)例程即語句:
Student.__init__(self,name)
第二種是通過super函數(shù),形如 super(child_class, child_object).parent_attribute(arg)。第一個(gè)參數(shù)表示調(diào)用父類的起始處,第二個(gè)參數(shù)表示類實(shí)例(一般使用self),父類方法的參數(shù)只有self時(shí),參數(shù)args不用寫。此外,類內(nèi)部使用時(shí),child_class, child_object也可省略。對(duì)應(yīng)例程:
super(Score,self).__init__(name)
后者
super().__init__(name)
在類外面也可使用super函數(shù),但是要有child_class, child_object兩個(gè)參數(shù)。更多學(xué)習(xí)內(nèi)容,請(qǐng)點(diǎn)擊Python學(xué)習(xí)網(wǎng)。
名稱欄目:創(chuàng)新互聯(lián)Python教程:python中子類可以調(diào)用父類方法嗎
文章起源:http://m.fisionsoft.com.cn/article/dhshjsg.html


咨詢
建站咨詢
