新聞中心
在python中,可以使用super()函數(shù)來(lái)調(diào)用基類的成員方法;語(yǔ)法為“super(type[, object-or-type])”。super()函數(shù)是用于調(diào)用父類(超類)的一個(gè)方法;可以用來(lái)解決多重繼承問(wèn)題。
創(chuàng)新互聯(lián)專業(yè)為企業(yè)提供克山網(wǎng)站建設(shè)、克山做網(wǎng)站、克山網(wǎng)站設(shè)計(jì)、克山網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁(yè)設(shè)計(jì)與制作、克山企業(yè)網(wǎng)站模板建站服務(wù),十載克山做網(wǎng)站經(jīng)驗(yàn),不只是建網(wǎng)站,更提供有價(jià)值的思路和整體網(wǎng)絡(luò)服務(wù)。
可以使用super()函數(shù):
例:
class Derived(Base): def meth(self): super(Derived,self).meth()
Python super() 函數(shù)
Python 內(nèi)置函數(shù)
描述
super() 函數(shù)是用于調(diào)用父類(超類)的一個(gè)方法。
super 是用來(lái)解決多重繼承問(wèn)題的,直接用類名調(diào)用父類方法在使用單繼承的時(shí)候沒(méi)問(wèn)題,但是如果使用多繼承,會(huì)涉及到查找順序(MRO)、重復(fù)調(diào)用(鉆石繼承)等種種問(wèn)題。
MRO 就是類的方法解析順序表, 其實(shí)也就是繼承父類方法時(shí)的順序表。
語(yǔ)法
以下是 super() 方法的語(yǔ)法:
super(type[, object-or-type])
參數(shù)
type -- 類。object-or-type -- 類,一般是 self
Python3.x 和 Python2.x 的一個(gè)區(qū)別是: Python 3 可以使用直接使用 super().xxx 代替 super(Class, self).xxx :
Python3.x 實(shí)例:
class A: def add(self, x): y = x+1
print(y)class B(A): def add(self, x): super().add(x)b = B()b.add(2) # 3
Python2.x 實(shí)例:
#!/usr/bin/python# -*- coding: UTF-8 -*- class A(object): # Python2.x 記得繼承 object def add(self, x): y = x+1 print(y)class B(A): def add(self, x): super(B, self).add(x)b = B()b.add(2) # 3
返回值
無(wú)。
實(shí)例
以下展示了使用 super 函數(shù)的實(shí)例:
實(shí)例
#!/usr/bin/python# -*- coding: UTF-8 -*-
class FooParent(object): def __init__(self): self.parent = 'I\'m the parent.'
print ('Parent')
def bar(self,message): print ("%s from Parent" % message)
class FooChild(FooParent): def __init__(self): # super(FooChild,self) 首先找到 FooChild 的父類(就是類 FooParent),然后把類 FooChild 的對(duì)象轉(zhuǎn)換為類 FooParent 的對(duì)象
super(FooChild,self).__init__()
print ('Child')
def bar(self,message): super(FooChild, self).bar(message)
print ('Child bar fuction')
print (self.parent)
if __name__ == '__main__': fooChild = FooChild()
fooChild.bar('HelloWorld')執(zhí)行結(jié)果:
ParentChildHelloWorld from ParentChild bar fuction I'm the parent.
推薦課程:python基礎(chǔ)語(yǔ)法全講解視頻(馬哥教育2014版)
網(wǎng)站標(biāo)題:創(chuàng)新互聯(lián)Python教程:Python中如何調(diào)用基類的成員方法
標(biāo)題URL:http://m.5511xx.com/article/ccoidpp.html


咨詢
建站咨詢

