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
Python str() function
The str() function in Python is an in-built function that takes an object as input and returns its string representation. It can be used to convert various data types into strings, which can then be used for printing, concatenation, and formatting. Letâs take a simple example to converting an Intege
3 min read
set() Function in python
set() function in Python is used to create a set, which is an unordered collection of unique elements. Sets are mutable, meaning elements can be added or removed after creation. However, all elements inside a set must be immutable, such as numbers, strings or tuples. The set() function can take an i
3 min read
sum() function in Python
The sum of numbers in the list is required everywhere. Python provides an inbuilt function sum() which sums up the numbers in the list. Pythonarr = [1, 5, 2] print(sum(arr))Output8 Sum() Function in Python Syntax Syntax : sum(iterable, start) iterable : iterable can be anything list , tuples or dict
3 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
round() function in Python
Python round() function is a built-in function available with Python. It will return you a float number that will be rounded to the decimal places which are given as input. If the decimal places to be rounded are not specified, it is considered as 0, and it will round to the nearest integer. In this
6 min read
Python Functions
Python Functions is a block of statements that return the specific task. The idea is to put some commonly or repeatedly done tasks 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 ov
11 min read
vars() function in Python
vars() method takes only one parameter and that too is optional. It takes an object as a parameter which may be a module, a class, an instance, or access the __dict__ attribute in Python. In this article, we will learn more about vars() function in Python. Python vars() Function Syntax Syntax: vars(
3 min read
Function Wrappers in Python
Function wrappers, also known as decorators, are a powerful and useful feature in Python that allows programmers to modify the behavior of a function or class without changing its actual code. Decorators enable wrapping another function to extend or alter its behavior dynamically at runtime.Example:
2 min read