Python staticmethod() Function
Last Updated :
03 Mar, 2025
Python staticmethod() function is used to convert a function to a static function. Static methods are independent of class instances, meaning they can be called on the class itself without requiring an object of the class.
Example:
Python
class Utility:
def msg(name):
return f"Hello, {name}!"
msg = staticmethod(msg) # Using staticmethod() function
# Calling the static method
print(Utility.msg("Vishakshi"))
Explanation: Utility class has a static method msg() that doesn’t need an object to work. It simply takes a name and returns "Hello, {name}!". Since it's a static method, we can call it directly using Utility.greet("Vishakshi") without creating an instance of the class.
Syntax of staticmethod()
staticmethod(function)
- Parameters: A function that needs to be converted into a static method.
- Returns: A static method version of the given function.
What are Static Methods in a Python
In object-oriented programming (OOP), a static method is a method that belongs to the class rather than an instance of the class. It is defined using the @staticmethod decorator and does not have access to instance-specific attributes (self) or class-specific attributes (cls).
Key characteristics of statics methods:
- Do not require instantiation of the class.
- Cannot modify the state of the class or instances.
- Useful for utility functions related to a class but independent of instance data.
When to Use Static Methods?
Static methods are useful in situations where a function is logically related to a class but does not require access to instance-specific data. Common use cases include:
- Utility functions (e.g., mathematical operations, string formatting).
- Operations that involve class-level data but do not need to modify it.
- Methods that do not rely on instance variables and should be accessible without object creation.
Examples of staticmethods() Usage
Example 1: Using staticmethod() for a Simple Utility Function
Python
class MathUtils:
def add(a, b):
return a + b
add = staticmethod(add) # Using staticmethod() function
# Calling the static method
res = MathUtils.add(9, 8)
print(res)
Explanation: MathUtils class has a static method add() that doesn’t need an object to work. It simply takes two numbers, adds them and returns the result.
Example 2: Static Method for Mathematical Operations
If a method does not use any class properties, it should be made static. However, methods that access instance variables must be called via an instance.
Python
class DemoClass:
def __init__(self, a, b):
self.a = a
self.b = b
def add(a, b):
return a + b
def diff(self):
return self.a - self.b
# Convert add() into a static method
DemoClass.add = staticmethod(DemoClass.add)
# Calling the static method without creating an instance
print(DemoClass.add(1, 2))
# Creating an instance to access instance-specific data
obj = DemoClass(1, 2)
print(obj.diff())
Explanation:
- Static Method (add()): It takes two numbers and returns their sum. Since it's static, we call it directly using DemoClass.add(1, 2), which prints 3.
- Instance Method (diff()): It accesses instance-specific values (self.a and self.b) and returns their difference. Calling obj.diff() for DemoClass(1, 2) returns -1.
Example 3: Accessing Class Variables Using a Static Method
Static methods cannot access instance attributes but can access class-level variables.
Python
class MathUtils:
num = 40 # Class variable
def double():
return MathUtils.num * 2
double = staticmethod(double) # Using staticmethod() function
# Calling the static method
res = MathUtils.double()
print(res)
Explanation: class variable num (40) is shared across instances. The static method double() directly accesses it and returns twice its value. Since it's static, we call it without creating an instance.
Example 4: Using a static method for string formatting
Python
class Formatter:
def format_name(first_name, last_name):
return f"{last_name}, {first_name}"
format_name = staticmethod(format_name) # Using staticmethod() function
# Calling the static method
res = Formatter.format_name("For Geeks", "Geeks")
print(res)
Explanation: Formatter class has a static method format_name() that takes a first and last name and returns them in "LastName, FirstName" format.
Why Use @staticmethod Instead of staticmethod()?
- Improved Readability: The @staticmethod decorator is placed directly above the method, making it clear that it's a static method.
- More Pythonic: Decorators are widely used in Python (@staticmethod, @classmethod, @property), so they align with common conventions.
- Easier Maintenance: Future modifications to the method are easier to manage without needing to manually reassign it with staticmethod().
Example: Using @staticmethod
Python
class Utility:
@staticmethod
def greet(name):
return f"Hello, {name}!"
# Calling the static method
print(Utility.greet("Vishakshi"))
Explanation: Using @staticmethod is the preferred approach as it enhances readability and follows Python's best practices. However, staticmethod() is still useful in cases where decorators are not an option (e.g., dynamically assigning methods).
Similar Reads
Python @staticmethod There can be some functionality that relates to the class, but does not require any instance(s) to do some work, static methods can be used in such cases. A static method is a method which is bound to the class and not the object of the class. It canât access or modify class state. It is present in
2 min read
type() function in Python The type() function is mostly used for debugging purposes. Two different types of arguments can be passed to type() function, single and three arguments. If a single argument type(obj) is passed, it returns the type of the given object. If three argument types (object, bases, dict) are passed, it re
5 min read
Get Function Signature - Python A function signature in Python defines the name of the function, its parameters, their data types , default values and the return type. It acts as a blueprint for the function, showing how it should be called and what values it requires. A good understanding of function signatures helps in writing c
3 min read
Python Functions Python Functions is a block of statements that does a specific task. The idea is to put some commonly or repeatedly done task together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it over an
9 min read
Python | How to get function name ? One of the most prominent styles of coding is following the OOP paradigm. For this, nowadays, stress has been to write code with modularity, increase debugging, and create a more robust, reusable code. This all encouraged the use of different functions for different tasks, and hence we are bound to
3 min read