In Python, both staticmethod
and classmethod
are used to define methods that belong to a class rather than an instance of that class. However, they differ in how they are bound to the class and how they handle arguments.
A staticmethod
is a method that belongs to the class and does not depend on the state of any instance of the class. It does not receive any special first argument, like self
or cls
, and can be called on the class itself or an instance of the class. Here’s an example:
class MyClass:
@staticmethod
def my_static_method(x, y):
return x + y
# Calling the static method on the class itself
result = MyClass.my_static_method(3, 4)
print(result)
# Calling the static method on an instance of the class
obj = MyClass()
result = obj.my_static_method(3, 4)
print(result)
7
7
As you can see, the my_static_method()
method does not take a special first argument, and it can be called on both the class and an instance of the class.
A classmethod
, on the other hand, is a method that also belongs to the class, but it receives a special first argument, conventionally named cls
, that refers to the class itself. This allows the method to access and modify the class-level state. Here’s an example:
class MyClass:
class_var = 0
@classmethod
def my_class_method(cls, x):
cls.class_var += x
return cls.class_var
# Calling the class method on the class itself
result = MyClass.my_class_method(3)
print(result)
# Calling the class method on an instance of the class
obj = MyClass()
result = obj.my_class_method(4)
print(result)
OUTPUT
3
7
As you can see, the my_class_method()
method takes a special first argument cls
, which refers to the class itself. The method can access and modify the class-level state, such as the class_var
variable in this example. The method can be called on both the class and an instance of the class, and the cls
argument is automatically bound to the class in both cases.
In summary, the main difference between staticmethod
and classmethod
is that the former does not receive a special first argument and does not depend on the state of any instance or the class itself, while the latter receives a special first argument that refers to the class itself and can access and modify the class-level state.
- sunny asked 1 month ago
- You must login to post comments
Please login first to submit.