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 delve into the details with examples:
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.
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.
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.
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.
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.