在 Python 中,方法本質是附著於類別的函數。未綁定時為「未綁定方法」(Py2) 或普通函數 (Py3)。
class Pizza:
def __init__(self, size):
self.size = size
def get_size(self):
return self.size
Pizza.get_size → 未綁定函數Pizza(42).get_size → 綁定方法,self 自動傳入p = Pizza(42); p.get_size() → 等同 Pizza.get_size(p)綁定方法擁有 __self__ 屬性指向實例。
@staticmethod:不需 selfclass Pizza:
@staticmethod
def mix_ingredients(x, y):
return x + y
self/cls,行為如普通函數Pizza.mix_ingredients is Pizza().mix_ingredients 為 True@classmethod:接收 clsclass Pizza:
radius = 42
@classmethod
def get_radius(cls):
return cls.radius
cls),而非實例Pizza.get_radius、Pizza().get_radius 皆綁定同一方法,cls 固定為 PizzaClass.method 為 unbound method,呼叫必須傳實例Class.method 為普通 function,可直接呼叫(需自行傳 self)abc 模組使用 abc.ABCMeta 和 @abstractmethod 強制子類別實作介面,屬進階設計模式,此處不贅述。
| 方法類型 | 裝飾器 | 第一參數 | 綁定對象 | 典型用途 |
|---|---|---|---|---|
| 實例方法 | 無 | self (實例) | 實例 | 操作實例狀態 |
| 靜態方法 | @staticmethod | 無 | 無 (類別/實例皆可) | 工具函數、不依賴狀態 |
| 類別方法 | @classmethod | cls (類別) | 類別 | 工廠方法、操作類別屬性 |