Junior — Middle
Explain what a static method is in Python and how to use it
sobes.tech AI
Answer from AI
A static method in Python is a class method that does not automatically take either the instance of the class (self) or the class itself (cls) as the first argument. It is defined using the @staticmethod decorator.
Such a method is used when a function is logically related to the class but does not depend on the state of a particular object or the class. This is convenient for utility functions that are related to the class but do not require access to its attributes.
Example of usage:
class MathUtils:
@staticmethod
def add(a, b):
return a + b
# Calling the static method
result = MathUtils.add(5, 3) # 8
Here, add is a static method that can be called without creating an instance of the class.