classmethod python
- User
classmethod python
- Assistant
In Python, a classmethod is a special method that is bound to a class instead of an instance of that class. It can be called on the class itself, rather than on an instance of the class.
To define a classmethod in Python, use the @classmethod decorator before the method definition. The first parameter of the classmethod should always be cls, which refers to the class itself.
Here's an example of a classmethod that returns the number of instances of a class:
class MyClass: count = 0 def __init__(self): MyClass.count += 1 @classmethod def get_instance_count(cls): return cls.count # create some instances of the class obj1 = MyClass() obj2 = MyClass() # call the classmethod on the class itself print(MyClass.get_instance_count()) # output: 2In this example, the get_instance_count() method is a classmethod because it's decorated with @classmethod. It returns the count of instances of the MyClass class, which is stored in the count class variable. The method is called on the class itself using MyClass.get_instance_count().