A static method in Python is a method that belongs to a class but does not depend on the class or its objects. It is used when a function is logically related to a class but does not need access to instance (self) or class (cls) data.
Static methods are defined using the @staticmethod decorator.
A static method is a method that:
self or cls as the first parameterclass ClassName:
@staticmethod
def method_name(parameters):
# code
class MathOperations:
@staticmethod
def add(a, b):
return a + b
print(MathOperations.add(5, 3))
Output
8
Explanation
add() does not depend on class or objectStatic methods can be called in two ways:
MathOperations.add(2, 3)
obj = MathOperations()
obj.add(2, 3)
class Converter:
@staticmethod
def celsius_to_fahrenheit(c):
return (c * 9/5) + 32
print(Converter.celsius_to_fahrenheit(25))
| Feature | Instance Method | Class Method | Static Method |
|---|---|---|---|
| First parameter | self |
cls |
None |
| Access | Instance variables | Class variables | No direct access |
| Decorator | None | @classmethod |
@staticmethod |
| Usage | Object-specific logic | Class-level logic | Utility functions |
Use static methods when:
@staticmethodself or clsclass Example:
def instance_method(self):
print("Instance Method")
@classmethod
def class_method(cls):
print("Class Method")
@staticmethod
def static_method():
print("Static Method")
obj = Example()
obj.instance_method()
Example.class_method()
Example.static_method()
@staticmethod decorator.