python中關(guān)于對(duì)super()函數(shù)疑問(wèn)解惑
案例一:運(yùn)行下面的代碼結(jié)果是什么?
class Person:
def run(self):
print('studying')
class Person1:
def run(self):
print('working')
class Person2:
def run(self):
print('playing')
class Person3(Person,Person1,Person2):
def run(self):
super().run1()
p=Person3()
p.run()
執(zhí)行結(jié)果:
AttributeError: ‘super’ object has no attribute ‘run1’
注意:
1、一個(gè)類(lèi)繼承多個(gè)類(lèi)時(shí),如果父類(lèi)中沒(méi)有提供該方法,類(lèi)會(huì)通過(guò)__mro__屬性一直向上搜索,如果直到object還沒(méi)有搜索到該方法,那么將會(huì)引發(fā)AttributeError異常
案例二:運(yùn)行下面的代碼結(jié)果是什么?
class Person:
def run(self):
print('studying')
class Person1:
def run(self):
print('working')
class Person2:
def run(self):
print('playing')
class Person3(Person,Person1,Person2):
def run(self):
super(Person1,self).run()
p=Person3()
p.run()
輸出結(jié)果為:playing;而不是working
注意:
1、super()函數(shù)的使用。
使用super()函數(shù)時(shí),可以通過(guò)super(類(lèi)名,self)來(lái)指定對(duì)哪個(gè)對(duì)象以哪個(gè)類(lèi)為起點(diǎn)向上搜索父類(lèi)中的方法。
例如:super(Person1,self).run():表示以Person1類(lèi)為起點(diǎn),向上搜索self(Person3的對(duì)象)的run方法。
Person1向上搜索到了<class ‘main.Person2’>,所以才會(huì)輸出playing
2、print(Person3.mro)的繼承順序?yàn)椋?<class ‘main.Person3’>, <class ‘main.Person’>, <class ‘main.Person1’>, <class ‘main.Person2’>, <class ‘object’>)
案例三、更復(fù)雜些的繼承,和上面的同理
class A:
def who(self):
print('A', end='')
class B(A):
def who(self):
super(B, self).who()
print('B', end='')
class C(A):
def who(self):
super(C, self).who()
print('C', end='')
class D(B, C):
def who(self):
super(D, self).who()
print('D', end='')
item = D()
item.who()
print(D.__mro__)
輸出結(jié)果:
ACBD
(<class ‘main.D’>, <class ‘main.B’>, <class ‘main.C’>, <class ‘main.A’>, <class ‘object’>)
總結(jié)
到此這篇關(guān)于python中關(guān)于對(duì)super()函數(shù)疑問(wèn)解惑的文章就介紹到這了,更多相關(guān)python super()函數(shù)解惑內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Pytorch數(shù)據(jù)讀取與預(yù)處理該如何實(shí)現(xiàn)
這篇文章主要介紹了Pytorch數(shù)據(jù)讀取與預(yù)處理該如何實(shí)現(xiàn),幫助大家更好的理解和學(xué)習(xí)使用Pytorch,感興趣的朋友可以了解下2021-03-03
詳解win10下pytorch-gpu安裝以及CUDA詳細(xì)安裝過(guò)程
這篇文章主要介紹了win10下pytorch-gpu安裝以及CUDA詳細(xì)安裝過(guò)程,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
python 實(shí)現(xiàn)提取log文件中的關(guān)鍵句子,并進(jìn)行統(tǒng)計(jì)分析
今天小編就為大家分享一篇python 實(shí)現(xiàn)提取log文件中的關(guān)鍵句子,并進(jìn)行統(tǒng)計(jì)分析,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-12-12
Python字典dict常用內(nèi)置函數(shù)詳解
這篇文章主要介紹了Python字典dict常用內(nèi)置函數(shù)詳解,dict是Python中的一種內(nèi)置數(shù)據(jù)類(lèi)型,它是一種鍵值對(duì)的集合,類(lèi)似于Java中的Map或其他語(yǔ)言中的字典,需要的朋友可以參考下2023-07-07
Pytorch使用DataLoader實(shí)現(xiàn)批量加載數(shù)據(jù)
這篇文章主要介紹了Pytorch使用DataLoader實(shí)現(xiàn)批量加載數(shù)據(jù)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-02-02
Python爬蟲(chóng)爬取有道實(shí)現(xiàn)翻譯功能
這篇文章主要介紹了Python爬蟲(chóng)爬取有道實(shí)現(xiàn)翻譯功能,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-11-11

