国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python之super的使用小結

2020-02-15 22:44:49
字體:
來源:轉載
供稿:網(wǎng)友

為什么需要super

在python沒有引入super之前, 如果需要在子類中引用父類的方法, 一般寫法如下:

class Father: def whoami(self):  print("I am father")class Child: def whoami(self):  print("I am child")  Father.whoami(self)

這樣看好像沒什么問題, 就算沒有super也能正常調用父類的方法, 但是如果有一天Father類需要修改類名為Father1, 那么子類Child中也必須跟著修改.

想象下如果一個類有很多個子類, 這樣一來我們就需要修改每個子類中引用父類的語句

怎么使用super

Help on class super in module builtins:class super(object) | super() -> same as super(__class__, <first argument>) | super(type) -> unbound super object | super(type, obj) -> bound super object; requires isinstance(obj, type) | super(type, type2) -> bound super object; requires issubclass(type2, type) | Typical use to call a cooperative superclass method: | class C(B): |   def meth(self, arg): |     super().meth(arg) | This works for class methods too: | class C(B): |   @classmethod |   def cmeth(cls, arg): |     super().cmeth(arg)

我們來看看super的幫助文檔, 首先super是一個類, 它的調用方法有如下幾種:

1.super()
2.super(type)
3.super(type, obj)
4.super(type, type2)

我們推薦用第一種方法來使用super, 因為它并不需要顯式傳遞任何參數(shù).但是要注意一點, super只能在新式類中使用.

class A: def __init__(self):  print("this is A")class B(A): def __init__(self):  super().__init__()  print("this is B")b = B()"""this is Athis is B"""

看起來super就像直接調用了B的父類A的__init__, 其實并不是這樣的, 我們看看super在多繼承下的使用

class A: def __init__(self):  print("this is A")  print("leave A")class B(A): def __init__(self):  print("this is B")  super().__init__()  print("leave B")class C(A): def __init__(self):  print("this is C")  super().__init__()  print("leave C") class D(B, C): def __init__(self):  print("this is D")  super().__init__()  print("leave D")    d = D()"""this is Dthis is Bthis is Cthis is Aleave Aleave Cleave Bleave D"""print(D.__mro__)"""(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)"""

這里可以看到, 如果super只是簡單調用父類的方法的話, 那么調用了B的__init__ 方法之后, 應該調用A的__init__ 才對, 但是調用的卻是C的__init__ 方法

這是因為super調用的是當前類在MRO列表中的后一個類, 而并不是簡單地調用當前類的父類

python并沒有強制性限制我們使用super調用父類, 我們還是可以使用原始的方法來調用父類中的方法, 但是需要注意的是調用父類的方法要統(tǒng)一, 即全用super或全不用super, 而用super 的話, 調用的方式也最好是統(tǒng)一的

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 平江县| 大城县| 青神县| 上犹县| 辉南县| 玛多县| 利辛县| 根河市| 海淀区| 黔江区| 邯郸县| 普安县| 尤溪县| 许昌县| 于田县| 宝清县| 凌海市| 鄢陵县| 资兴市| 威海市| 阳春市| 新野县| 盐山县| 玉门市| 周宁县| 屯门区| 平山县| 蒙城县| 洛川县| 鸡泽县| 富宁县| 九龙城区| 济宁市| 吉木萨尔县| 桐柏县| 湘乡市| 盐城市| 伊川县| 英吉沙县| 平安县| 齐齐哈尔市|