How to Create Static Methods in a Python Class
Shows how to define and call static methods inside a class using @staticmethod, with utility functions that don't need instance or class state.
Python code
25 linesclass MathUtils:
"""Utility class demonstrating static methods."""
@staticmethod
def add(a, b):
"""Return the sum of two numbers."""
return a + b
@staticmethod
def multiply(a, b):
"""Return the product of two numbers."""
return a * b
@staticmethod
def is_even(number):
"""Return True if number is even, False otherwise."""
return number % 2 == 0
if __name__ == "__main__":
# Calling static methods via the class namespace
print("Sum:", MathUtils.add(5, 3))
print("Product:", MathUtils.multiply(5, 3))
print("Is 4 even?", MathUtils.is_even(4))
print("Is 7 even?", MathUtils.is_even(7))
Output
Sum: 8
Product: 15
Is 4 even? True
Is 7 even? False
How it works
Static methods are decorated with @staticmethod and do not receive self or cls as the first argument. They behave like regular functions but live in the class namespace, which groups related utilities. Because they don't depend on instance state, you can call them directly on the class without creating an object. This makes them ideal for helper functions that logically belong to a class but don't need access to its attributes.
Common mistakes
- Forgetting the `@staticmethod` decorator, causing `self` to be passed as the first argument
- Creating an instance when not needed — static methods can be called on the class directly
- Expecting access to instance attributes inside a static method
Variations
- Use `@classmethod` when you need access to class-level state via `cls`
- Define the helper function outside the class for simpler use cases, then import it
Real-world use cases
- Utility math operations (like rounding or unit conversion) grouped under a namespace class.
- Validation helpers, e.g., checking email format, used across your codebase without instantiating objects.
- Factory-like utilities that create or transform objects but don't require instance state.
Sponsored
More from OOP & classes
- Add property getter setter validation in Python easy
- Binary Tree Inorder Traversal in Python easy
- Borg pattern shared state in Python medium
- Bridge Pattern in Python: Separate Abstraction from Implementation medium
- Composable Predicates with the &, |, ~ Operators in Python medium
- Composition over Inheritance: How to Build a Wallet Account in Python easy
Keep learning
Related tutorials and quizzes for this topic.