深入解析Python編程中super關(guān)鍵字的用法
官方文檔中關(guān)于super的定義說(shuō)的不是很多,大致意思是返回一個(gè)代理對(duì)象讓你能夠調(diào)用一些繼承過(guò)來(lái)的方法,查找的機(jī)制遵循mro規(guī)則,最常用的情況如下面這個(gè)例子所示:
class C(B):
def method(self, arg):
super(C, self).method(arg)
子類C重寫了父類B中同名方法method,在重寫的實(shí)現(xiàn)中通過(guò)super實(shí)例化的代理對(duì)象調(diào)用父類的同名方法。
super類的初始方法簽名如下:
def __init__(self, type1, type2=None): # known special case of super.__init__
"""
super(type, obj) -> bound super object; requires isinstance(obj, type)
super(type) -> unbound super object
super(type, type2) -> bound super object; requires issubclass(type2, type)
Typical use to call a cooperative superclass method:
除去self外接受一個(gè)或者或者兩個(gè)參數(shù),如同注釋聲明的一樣,接受兩個(gè)參數(shù)時(shí)返回的是綁定的super實(shí)例,省略第二個(gè)參數(shù)的時(shí)候返回的是未綁定的super對(duì)象。
一般情況下當(dāng)調(diào)用繼承的類方法或者靜態(tài)方法時(shí),并不需要綁定具體的實(shí)例,這個(gè)時(shí)候使用super(type, type2).some_method就能達(dá)到目的,當(dāng)然super(type, obj)在這種情況下也能夠使用,super對(duì)象有自定義實(shí)現(xiàn)的getattribute方法也能夠處理。不過(guò),后者一般用來(lái)調(diào)用實(shí)例方法,這樣在查找方法的時(shí)候能夠傳入相應(yīng)的實(shí)例,從而得到綁定的實(shí)例方法:
class A(object):
def __init__(self):
pass
@classmethod
def klass_meth(cls):
pass
@staticmethod
def static_meth():
pass
def test(self):
pass
class B(A):
pass
>>> b = B()
>>> super(B, b).test
<bound method B.test of <__main__.B object at 0x02DA3570>>
>>> super(B, b).klass_meth
<bound method type.klass_meth of <class '__main__.B'>>
>>> super(B, b).static_meth
<function static_meth at 0x02D9CC70>
>>> super(B, B).test
<unbound method B.test>
>>> super(B, B).klass_meth
<bound method type.klass_meth of <class '__main__.B'>>
>>> super(B,B).satic_meth
>>> super(B,B).static_meth
<function static_meth at 0x02D9CC70>
初始化super對(duì)象的時(shí)候,傳遞的第二個(gè)參數(shù)其實(shí)是綁定的對(duì)象,第一個(gè)參感覺數(shù)可以粗暴地理解為標(biāo)記查找的起點(diǎn),比如上面例子中的情況:super(B, b).test就會(huì)在B.__mro__里面列出的除B本身的類中查找方法test,因?yàn)榉椒ǘ际欠菙?shù)據(jù)描述符,在super對(duì)象的自定義getattribute里面實(shí)際上會(huì)轉(zhuǎn)化成A.__dict['test'].__get__(b, B)。
super在很多地方都會(huì)用到,除了讓程序不必hardcode指定類型讓代碼更加動(dòng)態(tài),還有其他一些具體必用的地方比如元類中使用super查找baseclass里面的new生成自定義的類型模板;在自定義getattribute的時(shí)候用來(lái)防止無(wú)限循環(huán)等等。
關(guān)于super建議讀者將它與python的描述符一起來(lái)理解,因?yàn)閟uper就實(shí)現(xiàn)了描述符的協(xié)議,是一個(gè)非數(shù)據(jù)描述符,能夠幫助大家更好的理解super的使用和工作原理。
同時(shí),有以下4個(gè)點(diǎn)值得大家注意:
1、單繼承時(shí)super()和__init__()實(shí)現(xiàn)的功能是類似的
class Base(object):
def __init__(self):
print 'Base create'
class childA(Base):
def __init__(self):
print 'creat A ',
Base.__init__(self)
class childB(Base):
def __init__(self):
print 'creat B ',
super(childB, self).__init__()
base = Base()
a = childA()
b = childB()
輸出結(jié)果:
Base create creat A Base create creat B Base create
使用super()繼承時(shí)不用顯式引用基類。
2、super()只能用于新式類中
把基類改為舊式類,即不繼承任何基類
class Base():
def __init__(self):
print 'Base create'
執(zhí)行時(shí),在初始化b時(shí)就會(huì)報(bào)錯(cuò):
super(childB, self).__init__() TypeError: must be type, not classobj
3、super不是父類,而是繼承順序的下一個(gè)類
在多重繼承時(shí)會(huì)涉及繼承順序,super()相當(dāng)于返回繼承順序的下一個(gè)類,而不是父類,類似于這樣的功能:
def super(class_name, self): mro = self.__class__.mro() return mro[mro.index(class_name) + 1]
mro()用來(lái)獲得類的繼承順序。
例如:
class Base(object):
def __init__(self):
print 'Base create'
class childA(Base):
def __init__(self):
print 'enter A '
# Base.__init__(self)
super(childA, self).__init__()
print 'leave A'
class childB(Base):
def __init__(self):
print 'enter B '
# Base.__init__(self)
super(childB, self).__init__()
print 'leave B'
class childC(childA, childB):
pass
c = childC()
print c.__class__.__mro__
輸入結(jié)果如下:
enter A enter B Base create leave B leave A (<class '__main__.childC'>, <class '__main__.childA'>, <class '__main__.childB'>, <class '__main__.Base'>, <type 'object'>)
supder和父類沒有關(guān)聯(lián),因此執(zhí)行順序是A —> B—>—>Base
執(zhí)行過(guò)程相當(dāng)于:初始化childC()時(shí),先會(huì)去調(diào)用childA的構(gòu)造方法中的 super(childA, self).__init__(), super(childA, self)返回當(dāng)前類的繼承順序中childA后的一個(gè)類childB;然后再執(zhí)行childB().__init()__,這樣順序執(zhí)行下去。
在多重繼承里,如果把childA()中的 super(childA, self).__init__() 換成Base.__init__(self),在執(zhí)行時(shí),繼承childA后就會(huì)直接跳到Base類里,而略過(guò)了childB:
enter A Base create leave A (<class '__main__.childC'>, <class '__main__.childA'>, <class '__main__.childB'>, <class '__main__.Base'>, <type 'object'>)
從super()方法可以看出,super()的第一個(gè)參數(shù)可以是繼承鏈中任意一個(gè)類的名字,
如果是本身就會(huì)依次繼承下一個(gè)類;
如果是繼承鏈里之前的類便會(huì)無(wú)限遞歸下去;
如果是繼承鏈里之后的類便會(huì)忽略繼承鏈匯總本身和傳入類之間的類;
比如將childA()中的super改為:super(childC, self).__init__(),程序就會(huì)無(wú)限遞歸下去。
如:
File "C:/Users/Administrator/Desktop/crawler/learn.py", line 10, in __init__ super(childC, self).__init__() File "C:/Users/Administrator/Desktop/crawler/learn.py", line 10, in __init__ super(childC, self).__init__() File "C:/Users/Administrator/Desktop/crawler/learn.py", line 10, in __init__ super(childC, self).__init__() File "C:/Users/Administrator/Desktop/crawler/learn.py", line 10, in __init__ super(childC, self).__init__() File "C:/Users/Administrator/Desktop/crawler/learn.py", line 10, in __init__ super(childC, self).__init__() File "C:/Users/Administrator/Desktop/crawler/learn.py", line 10, in __init__ super(childC, self).__init__() File "C:/Users/Administrator/Desktop/crawler/learn.py", line 10, in __init__ super(childC, self).__init__() File "C:/Users/Administrator/Desktop/crawler/learn.py", line 10, in __init__ super(childC, self).__init__() File "C:/Users/Administrator/Desktop/crawler/learn.py", line 10, in __init__ super(childC, self).__init__() File "C:/Users/Administrator/Desktop/crawler/learn.py", line 10, in __init__ super(childC, self).__init__() File "C:/Users/Administrator/Desktop/crawler/learn.py", line 10, in __init__ super(childC, self).__init__() File "C:/Users/Administrator/Desktop/crawler/learn.py", line 10, in __init__ super(childC, self).__init__() File "C:/Users/Administrator/Desktop/crawler/learn.py", line 10, in __init__ super(childC, self).__init__() RuntimeError: maximum recursion depth exceeded while calling a Python object
4、super()可以避免重復(fù)調(diào)用
如果childA基礎(chǔ)Base, childB繼承childA和Base,如果childB需要調(diào)用Base的__init__()方法時(shí),就會(huì)導(dǎo)致__init__()被執(zhí)行兩次:
class Base(object):
def __init__(self):
print 'Base create'
class childA(Base):
def __init__(self):
print 'enter A '
Base.__init__(self)
print 'leave A'
class childB(childA, Base):
def __init__(self):
childA.__init__(self)
Base.__init__(self)
b = childB()
Base的__init__()方法被執(zhí)行了兩次
enter A
Base create
leave A
Base create
使用super()是可避免重復(fù)調(diào)用
class Base(object):
def __init__(self):
print 'Base create'
class childA(Base):
def __init__(self):
print 'enter A '
super(childA, self).__init__()
print 'leave A'
class childB(childA, Base):
def __init__(self):
super(childB, self).__init__()
b = childB()
print b.__class__.mro()
enter A Base create leave A [<class '__main__.childB'>, <class '__main__.childA'>, <class '__main__.Base'>, <type 'object'>]
相關(guān)文章
postman傳遞當(dāng)前時(shí)間戳實(shí)例詳解
在本篇文章里小編給大家整理的是一篇關(guān)于postman傳遞當(dāng)前時(shí)間戳知識(shí)點(diǎn)相關(guān)內(nèi)容,有需要的朋友們可以學(xué)習(xí)下。2019-09-09
解決pycharm運(yùn)行程序出現(xiàn)卡住scanning files to index索引的問題
今天小編就為大家分享一篇解決pycharm運(yùn)行程序出現(xiàn)卡住scanning files to index索引的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-06-06
解決python訪問報(bào)錯(cuò):jinja2.exceptions.TemplateNotFound:index.html
這篇文章主要介紹了解決python訪問報(bào)錯(cuò):jinja2.exceptions.TemplateNotFound:index.html,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-12-12
淺談Python2.6和Python3.0中八進(jìn)制數(shù)字表示的區(qū)別
下面小編就為大家?guī)?lái)一篇淺談Python2.6和Python3.0中八進(jìn)制數(shù)字表示的區(qū)別。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-04-04
Python面向?qū)ο笾接袑傩院退接蟹椒☉?yīng)用案例分析
這篇文章主要介紹了Python面向?qū)ο笾接袑傩院退接蟹椒?結(jié)合具體案例形式簡(jiǎn)單分析了面向?qū)ο蟪绦蛟O(shè)計(jì)中私有屬性與私有方法的基本功能與使用注意事項(xiàng),需要的朋友可以參考下2019-12-12
python WindowsError的錯(cuò)誤代碼詳解
這篇文章主要介紹了python WindowsError的錯(cuò)誤代碼詳解,因?yàn)槲覀冊(cè)跁鴮憄ythone過(guò)程中,經(jīng)常會(huì)遇到這樣的錯(cuò)誤,特分享一下需要的朋友可以參考下2017-07-07
Python使用difflib標(biāo)準(zhǔn)庫(kù)實(shí)現(xiàn)查找文本間的差異
在文本處理和比較中,查找文本之間的差異是一項(xiàng)常見的任務(wù),本文將詳細(xì)介紹如何使用difflib模塊來(lái)查找文本之間的差異,包括單行和多行文本的比較、生成差異報(bào)告,需要的可以參考下2024-03-03

