1. 程式人生 > 程式設計 >python super()函式的基本使用

python super()函式的基本使用

super主要來呼叫父類方法來顯示呼叫父類,在子類中,一般會定義與父類相同的屬性(資料屬性,方法),從而來實現子類特有的行為。也就是說,子類會繼承父類的所有的屬性和方法,子類也可以覆蓋父類同名的屬性和方法。

class Parent(object):
  Value = "Hi,Parent value"
 
  def fun(self):
    print("This is from Parent")
 
 
# 定義子類,繼承父類
class Child(Parent):
  Value = "Hi,Child value"
 
  def ffun(self):
    print("This is from Child")
 
 
c = Child()
c.fun()
c.ffun()
print(Child.Value)
 
# 輸出結果
# This is from Parent
# This is from Child
# Hi,Child value

但是,有時候可能需要在子類中訪問父類的一些屬性,可以通過父類名直接訪問父類的屬性,當呼叫父類的方法是,需要將”self”顯示的傳遞進去的方式。

class Parent(object):
  Value = "Hi,Parent value"
 
  def fun(self):
    print("This is from Parent")
 
 
class Child(Parent):
  Value = "Hi,Child value"
 
  def fun(self):
    print("This is from Child")
    # 呼叫父類Parent的fun函式方法
    Parent.fun(self)
 
 
c = Child()
c.fun()
 
# 輸出結果
# This is from Child
# This is from Parent
# 例項化子類Child的fun函式時,首先會列印上條的語句,再次呼叫父類的fun函式方法

這種方式有一個不好的地方就是,需要經父類名硬編碼到子類中,為了解決這個問題,可以使用Python中的super關鍵字。

class Parent(object):
  Value = "Hi,Child value"
 
  def fun(self):
    print("This is from Child")
    # Parent.fun(self)
    # 相當於用super的方法與上一呼叫父類的語句置換
    super(Child,self).fun()
 
 
c = Child()
c.fun()
 
# 輸出結果
# This is from Child
# This is from Parent
# 例項化子類Child的fun函式時,首先會列印上條的語句,再次呼叫父類的fun函式方法

以上就是python super()函式的基本使用的詳細內容,更多關於python super()函式的資料請關注我們其它相關文章!