Junior — Middle
Can you explain the purpose and usage of the @classmethod decorator in Python?
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 instead of an instance.
This means that the method can work with class attributes and other class methods, rather than specific object data.
Example:
class MyClass:
count = 0
def __init__(self):
MyClass.count += 1
@classmethod
def get_count(cls):
return cls.count
obj1 = MyClass()
obj2 = MyClass()
print(MyClass.get_count()) # Outputs 2
Here, get_count is a class method that returns the number of objects created. cls is a reference to the class itself, similar to self for an instance.
It is used when working with class state or creating alternative constructors.