What is the difference between @staticmethod and @classmethod in Python?


In Python, the @staticmethod and @classmethod decorators are used to defining methods within a class. The difference between these two decorators lies in the way they handle the arguments passed to them.


A @staticmethod is a method that belongs to the class and does not require an instance of the class to be called. This means that it cannot access the instance variables of the class, nor can it modify them. It is used when you want to create a method that is related to the class but does not depend on the instance state. Here is an example of a @staticmethod:

class MyClass:
    @staticmethod
    def my_static_method(x, y):
        return x + y


You can call this method on the class itself, without creating an instance of the class:

result = MyClass.my_static_method(3, 4)


A @classmethod is a method that takes the class itself as its first argument, rather than an instance of the class. It is commonly used to create alternative constructors for a class. Here is an example of a @classmethod:

class MyClass:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    @classmethod
    def from_string(cls, string):
        x, y = map(int, string.split(','))
        return cls(x, y)

In this example, the from_string method takes a string as input and returns an instance of the class. It uses the cls parameter to create the instance. You can call this method on the class itself, without creating an instance of the class:

obj = MyClass.from_string('1,2')

In summary, the @staticmethod decorator creates a method that does not require an instance of the class to be called, while the @classmethod decorator creates a method that takes the class itself as its first argument and is commonly used to create alternative constructors.

Leave a Reply

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