Middle
What are the differences between the @classmethod and @staticmethod decorators in Python?
sobes.tech AI
Answer from AI
@classmethod takes the class reference (cls) as the first argument, automatically passed by the interpreter during the call. It is used for creating factory methods or methods that work with class attributes.
@staticmethod does not implicitly take the class or instance as the first argument. Essentially, it is a regular function defined within a class for logical grouping. It does not have access to the instance or class state.
class MyClass:
count = 0
def __init__(self, value):
self.value = value
MyClass.count += 1
@classmethod
def create_from_value(cls, value):
# Class method, has access to the class MyClass via cls
return cls(value)
@staticmethod
def display_info(item):
# Static method, has no access to class or instance
print(f"Object value: {item.value}")
# Usage
obj1 = MyClass(10)
obj2 = MyClass.create_from_value(20) # Call via class method
MyClass.display_info(obj1) # Call static method
# MyClass.display_info(MyClass) # Does not work if the method expects an instance
| Characteristic | @classmethod |
@staticmethod |
|---|---|---|
| First argument | Reference to the class (cls) |
None |
| Access to state | Class | Neither instance nor class |
| Main purpose | Factory methods, working with class attributes | Logical grouping of functions within a class |
| Call | Via instance or class | Via instance or class |