In Python OOPs, a Static Method is a method inside a class that does not depend on the instance (self
) or the class (cls
).
It behaves just like a normal function, but is placed inside a class for logical grouping.
Declared using @staticmethod
decorator.
It cannot access or modify instance variables (self
) or class variables (cls
).
It belongs to the class namespace, not to objects.
class MyClass:
@staticmethod
def greet(name):
return f"Hello, {name}!"
Usage:
print(MyClass.greet("Abhi")) # Calling via class
obj = MyClass()
print(obj.greet("Agnihotri")) # Calling via object
✅ Both calls work the same way!
Utility functions → Functions that don’t need self
or cls
.
Code organization → Keep related functions inside the class.
Avoid unnecessary instantiation → Call without creating objects.
class MathUtils:
class_var = 10 # Class variable
def instance_method(self, x):
return x + self.class_var # Needs object (self)
@classmethod
def class_method(cls, x):
return x + cls.class_var # Needs class (cls)
@staticmethod
def static_method(x, y):
return x + y # No self, no cls
obj = MathUtils()
print(obj.instance_method(5)) # 15 → uses self
print(MathUtils.class_method(5)) # 15 → uses cls
print(MathUtils.static_method(3, 7)) # 10 → no self/cls needed
✅ When method logic doesn’t depend on instance (self
) or class (cls
).
✅ For helper/utility functions (e.g., validators, formatters, calculations).
❌ Don’t use when you need to access or modify class/instance variables.
✨ In short:
@staticmethod
= A function inside a class, but independent of object/class.
It’s just there for better code organization.