Python

What is @classmethod?

7 months, 3 weeks ago ; 218 views
Share this

What is @classmethod?

In Python, the @classmethod decorator defines a class method within a class.

A class method is a method that is bound to the class and not the instance of the class. It takes the class as its first argument, conventionally named cls, and can be called on the class itself or an instance of the class.

Here's an example of using @classmethod:

class ClassMethod:
    class_variable = "I am a class variable"

    def __init__(self, value):
        self.value = value

    @classmethod
    def class_method(cls):
        print("This is a class method")
        print(f"Accessing class variable: {cls.class_variable}")

# Creating an instance of the class
obj = ClassMethod(value=189)

# Accessing the class method using the class itself
ClassMethod.class_method()  # Output: This is a class method

# Accessing the class method using an instance
obj.class_method()  # Output: This is a class method

Key points about @classmethod:

  • It is a decorator that defines a method as a class method.
  • Class methods are bound to the class and have access to class-level attributes.
  • They take the class, conventionally named cls, as the first argument.
  • They can be called on the class itself or an instance of the class.

Class methods are often used when performing operations involving the class rather than a specific instance. They are useful for creating alternative constructors, accessing class-level attributes, or performing other class-level operations.

Here's an example of a class method as an alternative constructor:

class ClassMethod:
    def __init__(self, value):
        self.value = value

    @classmethod
    def create_instance(cls, value):
        # Using the class to create an instance
        return cls(value=value)

# Using the class method to create an instance
obj = ClassMethod.create_instance(value=189)

In this example, create_instance is a class method used to create an instance of the class.

 

Become a member
Get the latest news right in your inbox. We never spam!

Read next

Island Perimeter

 This solution seeks to find the perimeter of an island in a grid.  The problem considers a grid where each cell represents land (1) or … Read More

Kibsoft 4 months, 1 week ago . 91 views

Pacific Atlantic Waterflow

4 months, 1 week ago . 95 views