Python staticmethod()
Function
The staticmethod() function in Python is used to define a static method inside a class. A static method doesn't take the instance (self
) or class (cls
) as the first argument. It behaves like a regular function but belongs to the class’s namespace.
Syntax
staticmethod(function)
Parameter:
function
– A function you want to convert into a static method.
Returns:
- A static method object that can be called on the class or its instances.
Example: Creating a Static Method
class MathUtils:
@staticmethod
def add(a, b):
return a + b
# Call without creating an object
print(MathUtils.add(5, 3))
8
Example: Without Decorator
You can also use staticmethod()
without the @staticmethod
decorator:
class MathUtils:
def add(a, b):
return a + b
add = staticmethod(add)
print(MathUtils.add(10, 4))
14
Use Case: When to Use staticmethod()
?
- When the method doesn’t need access to the instance or class.
- Utility functions that logically belong to the class, but don’t use class or instance data.
Comparison: staticmethod vs classmethod
Feature | staticmethod() | classmethod() |
---|---|---|
Access to instance? | No | No |
Access to class? | No | Yes |
First argument | None | cls |
Use case | Helper functions | Factory methods |
Common Mistakes
- Trying to use
self
orcls
inside a static method – it won’t work. - Not using
@staticmethod
decorator orstaticmethod()
function – method acts as a normal one and expectsself
.
Interview Tip
Interviewers often ask the difference between staticmethod()
and classmethod()
. Know when and why to use each.
Summary
staticmethod()
makes a function callable via the class without needing an object.- It doesn’t access or modify class or instance state.
- Perfect for utility/helper methods inside a class.
Practice Problem
Create a class Temperature
with a static method celsius_to_fahrenheit(c)
that converts Celsius to Fahrenheit.
class Temperature:
@staticmethod
def celsius_to_fahrenheit(c):
return (c * 9/5) + 32
print(Temperature.celsius_to_fahrenheit(37))
Expected Output:
98.6