In Python, a classmethod
is a decorator used to define a method that is bound to the class and not the instance of the class. This means you can call a class method on the class itself without creating an instance of the class. Class methods are often used for tasks that involve the class itself or its class-level attributes, rather than instance-specific data.
Here’s how you define and use a class method in Python:
class MyClass:
class_variable = "I am a class variable"
def __init__(self, instance_variable):
self.instance_variable = instance_variable
@classmethod
def class_method(cls, arg1, arg2):
# cls refers to the class itself, not an instance
print(f"Class variable: {cls.class_variable}")
print(f"Arguments: {arg1}, {arg2}")
# Create an instance of MyClass
obj = MyClass("Instance Variable")
# Call the class method on the class itself
MyClass.class_method("Argument 1", "Argument 2")
In the example above:
- We define a class called
MyClass
, which has a class variableclass_variable
and an instance variableinstance_variable
. - We define a class method called
class_method
using the@classmethod
decorator. This method takescls
as its first argument, which refers to the class itself. It can access class-level attributes likeclass_variable
. - We create an instance of
MyClass
and call the class methodclass_method
on the class itself, passing it two arguments. Note that we don’t need to create an instance to call the class method.
Class methods are useful in situations where you need to perform operations on class-level data or manipulate class-level attributes without the need for an instance of the class. They are often used for factory methods and for creating alternative constructors.