# Python中super()函數如何使用
## 一、super()函數概述
### 1.1 什么是super()函數
`super()`是Python內置函數,用于在子類中調用父類(超類)的方法。它返回一個代理對象,該對象會將方法調用委托給父類或兄弟類。
### 1.2 super()的作用
- 避免顯式引用基類名稱
- 實現多重繼承的方法調用順序(MRO)
- 解決鉆石繼承(菱形繼承)問題
- 使代碼更易維護(當基類改變時不需要修改所有子類)
## 二、基本語法和使用場景
### 2.1 基本語法
```python
super([type[, object-or-type]])
class Child(Parent):
def __init__(self):
super().__init__() # Python 3簡寫形式
# 等同于 super(Child, self).__init__()
@classmethod
def method(cls):
super().method() # Python 3
# 等同于 super(Child, cls).method()
class Parent:
def __init__(self, name):
self.name = name
print("Parent __init__")
class Child(Parent):
def __init__(self, name, age):
super().__init__(name) # 調用父類初始化
self.age = age
print("Child __init__")
c = Child("Alice", 10)
class Parent:
def show(self):
print("Parent show")
class Child(Parent):
def show(self):
super().show() # 先調用父類方法
print("Child show")
Python使用C3線性化算法確定方法調用順序,可通過ClassName.__mro__
查看
class A:
def show(self):
print("A")
class B(A):
def show(self):
print("B")
super().show()
class C(A):
def show(self):
print("C")
super().show()
class D(B, C):
def show(self):
print("D")
super().show()
d = D()
d.show()
print(D.__mro__) # 顯示方法解析順序
class Base:
def __init__(self):
print("Base")
class A(Base):
def __init__(self):
print("A")
super().__init__()
class B(Base):
def __init__(self):
print("B")
super().__init__()
class C(A, B):
def __init__(self):
print("C")
super().__init__()
c = C()
print(C.__mro__)
class Parent:
@classmethod
def create(cls):
print("Parent create")
return cls()
class Child(Parent):
@classmethod
def create(cls):
print("Child create")
return super().create()
靜態方法中不能直接使用super(),因為缺少必要的參數:
class Parent:
@staticmethod
def helper():
print("Parent helper")
class Child(Parent):
@staticmethod
def helper():
print("Child helper")
# 必須顯式指定父類
Parent.helper()
class Descriptor:
def __get__(self, obj, objtype=None):
return super().__get__(obj, objtype)
class Parent:
def __init__(self, x):
self.x = x
class Child(Parent):
def __init__(self, x, y):
super().__init__(x) # 必須顯式傳遞x
self.y = y
class Parent:
def __init__(self):
print("Parent")
self.setup()
def setup(self):
print("Parent setup")
class Child(Parent):
def __init__(self):
print("Child")
super().__init__()
def setup(self):
print("Child setup") # 會覆蓋父類的setup
class A:
def __init__(self, a):
self.a = a
class B:
def __init__(self, b):
self.b = b
class C(A, B):
def __init__(self, a, b):
super().__init__(a) # 只會調用A.__init__
B.__init__(self, b) # 需要顯式調用
__init__
方法接受并傳遞**kwargs
class Base:
def __init__(self, **kwargs):
super().__init__(**kwargs) # 確保鏈式調用
self.base_init()
class A(Base):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.a_init()
class B(Base):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.b_init()
class C(A, B):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.c_init()
super()
是Python面向對象編程中強大的工具,它:
- 簡化了父類方法的調用
- 正確處理了多重繼承場景
- 使代碼更易于維護
- 遵循Python的”顯式優于隱式”哲學
正確理解和使用super()需要掌握: 1. 方法解析順序(MRO) 2. 不同Python版本中的語法差異 3. 在單繼承和多繼承中的不同表現 4. 與類方法、靜態方法的交互
通過合理使用super(),可以構建出更清晰、更靈活的類層次結構。
”`
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。