初學者@classmethod和@staticmethod的含義和用法
在Python中,@classmethod和@staticmethod是用於定義方法的裝飾器具體的特徵。
@classmethod
類別方法是綁定到類別的方法,而不是綁定到類別的單一實例的方法。它必須有一個類別作為其第一個參數,通常命名為 cls。依照慣例,類別方法以 from_ 或 create_ 前綴命名。
何時使用 @classmethod:
範例:
class Date: def __init__(self, day, month, year): self.day = day self.month = month self.year = year @classmethod def from_string(cls, date_as_string): day, month, year = map(int, date_as_string.split('-')) return cls(day, month, year)
@staticmethod
靜態方法是一種不是方法綁定到類別或實例。它無權存取任何實例或類別變數。靜態方法通常用於無需修改即可重複使用的實用函數。
何時使用@staticmethod:
範例:
class Date: @staticmethod def is_date_valid(date_as_string): day, month, year = map(int, date_as_string.split('-')) return day <= 31 and month <= 12 and year <= 3999
class@class@class和@staticmethod
Feature | @classmethod | @staticmethod |
---|---|---|
Access to class | Has access to the class | No access to the class |
Access to instance | No access to instances | No access to instances |
Usage | Factory methods, operations on the class | Utility functions, independent of class or instances |
以上是Python 中的「@classmethod」和「@staticmethod」有什麼不同?的詳細內容。更多資訊請關注PHP中文網其他相關文章!