Class method Vs Static method

In Python, both @staticmethod and @classmethod decorators are used to define methods that are associated with a class rather than with an instance. However, they serve slightly different purposes and have distinct behavior. Let's investigate into the details with examples:

@staticmethod

A static method is a method that is bound to a class and not to the instances of the class. It doesn't receive any special first parameter (such as self for instance methods or cls for class methods). It behaves like a regular function but is scoped within the class.

class MathUtils: @staticmethod def add(x, y): return x + y result = MathUtils.add(5, 3) print("Result of addition:", result) # Output: Result of addition: 8

In the example above, the add method is a static method. It can be called using the class name (MathUtils.add(5, 3)), and it doesn't have access to instance-specific or class-specific data.

@classmethod

A class method is a method that is bound to the class and not the instance. It receives the class itself as the first parameter, conventionally named cls. This allows you to access and modify class-level attributes and methods.

class Circle: pi = 3.14159 def __init__(self, radius): self.radius = radius @classmethod def set_pi(cls, new_pi): cls.pi = new_pi circle1 = Circle(5) circle2 = Circle(8) print("Original pi:", Circle.pi) # Output: Original pi: 3.14159 Circle.set_pi(3.14) print("Updated pi:", Circle.pi) # Output: Updated pi: 3.14

In the example above, the set_pi method is a class method. It is used to modify the class attribute pi across all instances of the class. By receiving the class (cls) as an argument, it can access and modify class-level data.

Conclusion

The @staticmethod is used when a method doesn't require access to instance or class data, while @classmethod is used when a method needs access to and potentially modifies class-level attributes. Both decorators provide ways to define methods that are bound to the class rather than instances.