Python super超类方法
生活随笔
收集整理的這篇文章主要介紹了
Python super超类方法
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
super() 函數(shù)是用于調(diào)用父類(超類)的一個(gè)方法。
super 是用來解決多重繼承問題的,直接用類名調(diào)用父類方法在使用單繼承的時(shí)候沒問題,但是如果使用多繼承,會(huì)涉及到查找順序(MRO)、重復(fù)調(diào)用(鉆石繼承)等種種問題。
MRO 就是類的方法解析順序表, 其實(shí)也就是繼承父類方法時(shí)的順序表。
語法
以下是 super() 方法的語法:
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:pass class B(A):def add(self, x):super().add(x) Python2.x 實(shí)例: class A(object): # Python2.x 記得繼承 objectpass class B(A):def add(self, x):super(B, self).add(x)返回值
無。
實(shí)例
以下展示了使用 super 函數(shù)的實(shí)例:
執(zhí)行結(jié)果:
Parent Child HelloWorld from Parent Child bar fuction I'm the parent.總結(jié)
以上是生活随笔為你收集整理的Python super超类方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python flask解决上传下载的问
- 下一篇: Python 内编写类的各种技巧和方法