Skip to content

python classmethod

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

    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:

  1. We define a class called MyClass, which has a class variable class_variable and an instance variable instance_variable.
  2. We define a class method called class_method using the @classmethod decorator. This method takes cls as its first argument, which refers to the class itself. It can access class-level attributes like class_variable.
  3. We create an instance of MyClass and call the class method class_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.

Leave a Reply

Your email address will not be published. Required fields are marked *


Enjoy this blog? Please spread the word :)