Junior — Middle
What is the purpose of the @staticmethod decorator in Python and how does it differ from regular class methods?
sobes.tech AI
Answer from AI
The @staticmethod decorator in Python is used to define a method inside a class that does not depend on the class instance and does not automatically take the self parameter.
Differences from regular methods:
- Regular methods take
selfas the first parameter — a reference to the current instance of the class. - Static methods do not take
selforcls(a reference to the class).
This means that a static method is simply a function that is logically related to the class but does not use its state.
Example:
class MyClass:
@staticmethod
def static_method(x, y):
return x + y
def instance_method(self, x, y):
return x * y
print(MyClass.static_method(3, 4)) # 7
obj = MyClass()
print(obj.instance_method(3, 4)) # 12
Static methods are useful for utility functions that make sense in the context of the class but do not require access to its data.