Junior — Middle
Can you explain how the @classmethod decorator works in Python and what it is used for?
sobes.tech AI
Answer from AI
The @classmethod decorator in Python is used to define a class method that receives the class itself as the first argument (cls) instead of an instance (self). This allows calling the method on the class itself or on instances, and working with the class rather than a specific object.
Main features:
- The first parameter of the method is
cls, a reference to the class. - The method can create new instances of the class or modify class properties.
- It is called via
ClassName.method()orinstance.method().
Example:
class MyClass:
count = 0
def __init__(self):
MyClass.count += 1
@classmethod
def get_count(cls):
return cls.count
# Usage
obj1 = MyClass()
obj2 = MyClass()
print(MyClass.get_count()) # Outputs: 2
print(obj1.get_count()) # Also outputs: 2
Thus, @classmethod is useful for working with class state, factory methods, and other cases where the class itself is operated on rather than an individual object.