What is the difference between @staticmethod and @classmethod?
What is the difference between @staticmethod and @classmethod?
412
11-Apr-2023
Aryan Kumar
17-Apr-2023@staticmethod and @classmethod are two different decorators used to define methods inside a class. The main difference between them is how they handle the first parameter of the method
@staticmethod is used to define a method that does not take any special first argument. It is similar to a regular function outside of a class, but is defined inside a class. @staticmethod does not receive any reference to the instance of the class, nor to the class itself.
@classmethod is used to define a method that takes a reference to the class itself as its first argument. This first argument is usually called cls by convention, instead of self. This allows the method to access the class and its attributes.
class MyClass:
@staticmethod
def my_static_method(x, y):
return x + y
result = MyClass.my_static_method(3, 5)
print(result) # Output: 8
class MyClass:class_variable = 10@classmethoddef my_class_method(cls, x):return cls.class_variable + xresult = MyClass.my_class_method(5)print(result) # Output: 15Krishnapriya Rajeev
14-Apr-2023We use the @staticmethod and @classmethod decorators in Python to define methods within a class, but each of them has different purposes and uses.
The @staticmethod decorator is used to define a method that does not access or modify the state of an instance, and a special first argument is not passed. It is similar to a regular function that is defined outside the class, but it is within the scope of the class and can be called using the class name or an instance of the class.
This is a static method
The @classmethod decorator is used to define a method that operates on the class and receives the class itself as the first argument, which is conventionally named cls. This method can access and modify the state of the class or create new instances of the class. It can also be called using the name of the class or an instance of the class.