欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python之super的使用小結(jié)

 更新時間:2018年08月13日 09:49:34   作者:Dear、  
這篇文章主要介紹了python之super的使用小結(jié),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

為什么需要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也能正常調(diào)用父類的方法, 但是如果有一天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是一個類, 它的調(diào)用方法有如下幾種:

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

我們推薦用第一種方法來使用super, 因?yàn)樗⒉恍枰@式傳遞任何參數(shù).但是要注意一點(diǎn), 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 A
this is B
"""

看起來super就像直接調(diào)用了B的父類A的__init__, 其實(shí)并不是這樣的, 我們看看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 D
this is B
this is C
this is A
leave A
leave C
leave B
leave D
"""

print(D.__mro__)
"""
(<class '__main__.D'>, 
<class '__main__.B'>, 
<class '__main__.C'>, 
<class '__main__.A'>, 
<class 'object'>)
"""

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

這是因?yàn)閟uper調(diào)用的是當(dāng)前類在MRO列表中的后一個類, 而并不是簡單地調(diào)用當(dāng)前類的父類

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

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論