首頁 >後端開發 >Python教學 >Python 中的「@classmethod」和「@staticmethod」有什麼不同?

Python 中的「@classmethod」和「@staticmethod」有什麼不同?

Barbara Streisand
Barbara Streisand原創
2024-12-22 10:16:46332瀏覽

What's the Difference Between `@classmethod` and `@staticmethod` in Python?

初學者@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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn