The staticmethod() function converts a method into a static method, which means it belongs to the class but does not require access to instance (self) or class (cls) attributes. It’s useful for utility functions inside a class, code organization, and keeping logic related to a class inside it.
Example
class MathUtils:
@staticmethod
def add(a, b):
return a + b
print(MathUtils.add(3, 5))
Output:
8
The method does not need an instance to be called.
Syntax
staticmethod(function)
or use the @staticmethod decorator:
@staticmethod
def method_name():
pass
- Returns → A static method that does not require
selforcls.
1. Using staticmethod() to Define a Class Utility Method
class Math:
@staticmethod
def multiply(a, b):
return a * b
print(Math.multiply(4, 5)) # Output: 20
Since multiply() does not use self or cls, making it a static method keeps it logically inside the class.
2. Using staticmethod() Inside a Class
class Greeting:
@staticmethod
def say_hello():
return "Hello, World!"
print(Greeting.say_hello())
# Output: Hello, World!
staticmethod() groups functions inside a class without requiring an instance.
3. Calling a Static Method from an Instance
class Utils:
@staticmethod
def is_even(n):
return n % 2 == 0
u = Utils()
print(u.is_even(10)) # Output: True
You can call static methods from an instance, but it’s recommended to use the class name.
4. Using staticmethod() for Factory Methods
class Converter:
@staticmethod
def inches_to_cm(inches):
return inches * 2.54
print(Converter.inches_to_cm(10))
# Output: 25.4
Useful for converting values without modifying the class or instance.
5. Difference Between @staticmethod and @classmethod
| Decorator | Uses self? |
Uses cls? |
Can Access Class Attributes? | Example Use Case |
|---|---|---|---|---|
@staticmethod |
❌ No | ❌ No | ❌ No | Utility functions |
@classmethod |
❌ No | ✅ Yes | ✅ Yes | Factory methods |
class Example:
class_var = "Hello"
@staticmethod
def static_method():
return "I do not use self or cls."
@classmethod
def class_method(cls):
return cls.class_var # Access class attribute
print(Example.static_method()) # Output: I do not use self or cls.
print(Example.class_method()) # Output: Hello
Key Notes
- ✔ Creates a method that doesn’t use
selforcls. - ✔ Keeps related functions inside the class for better organization.
- ✔ Can be called without creating an instance.
- ✔ Use
@staticmethodinstead ofstaticmethod(function)for better readability.
By using staticmethod(), you can organize utility functions inside classes, make code cleaner, and avoid unnecessary instance dependencies. 🚀