Q31: What is the purpose of the @staticmethod decorator in Python, and how does it differ from the @classmethod decorator? Provide an example to illustrate their usage.
A31:
Purpose of
@staticmethodand@classmethod:The
@staticmethoddecorator in Python is used to define a static method within a class. Static methods are associated with the class rather than instances and do not have access to instance-specific data.The
@classmethoddecorator is used to define a class method within a class. Class methods take the class itself as the first parameter, allowing them to work with class-level data.
Difference and Example:
@staticmethoddoes not take the instance or class as its first parameter, making it independent of instance or class-specific data.@classmethodtakes the class as its first parameter, allowing access to class-specific data.
class MathOperations: @staticmethod def add(x, y): return x + y @classmethod def multiply(cls, x, y): return x * y # Using static method result_add = MathOperations.add(3, 5) # Using class method result_multiply = MathOperations.multiply(3, 5)In this example,
addis a static method, andmultiplyis a class method. Theaddmethod does not have access to the instance or class, while themultiplymethod can access class-specific data through theclsparameter.