Meaning and Usage of @classmethod and @staticmethod for Beginners
In Python, @classmethod and @staticmethod are decorators used to define methods with specific characteristics.
@classmethod
A classmethod is a method that is bound to a class, not to an individual instance of the class. It must have a class as its first argument, which is typically named cls. By convention, classmethods are named with from_ or create_ prefixes.
When to use @classmethod:
Example:
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
A staticmethod is a method that is not bound to either the class or an instance. It does not have access to any instance or class variables. Staticmethods are typically used for utility functions that can be reused without modification.
When to use @staticmethod:
Example:
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
Difference between @classmethod and @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 |
The above is the detailed content of What's the Difference Between `@classmethod` and `@staticmethod` in Python?. For more information, please follow other related articles on the PHP Chinese website!