Python staticmethod() Function
Last Updated :
10 Jul, 2024
Python staticmethod() function is used to convert a function to a static function. A static method is a method that belongs to a class rather than an instance of a class. The static methods do not require instantiation.
Python Staticmethod() Syntax
Syntax: staticmethod(function)
Parameter: The static method () method takes a single argument i.e. it takes a function as an argument.
Returns: The static method () returns a static method of the function passed as the argument.
What are Static Methods in a Python
In object-oriented programming, a static method is a special type of method that is associated with the class itself instead of any instance or object of the class. It can be directly called on the class without creating an instance of it. Python uses a decorator denoted by ‘@staticmethod’ to identify static methods.
When do you use static methods?
Static methods are used in specific situations where the functionality of a method is related to a class but doesn’t require access to instance-specific data. In certain situations, static methods are utilized when a method’s purpose is linked to a class but does not need access to data specific to an instance. They are beneficial for defining utility functions or operations that are closely tied to a class but do not rely on the state of individual objects.
Python Staticmethod() Example
The staticmethod() function in Python enables the definition of static methods within a class, allowing the creation of methods that do not require access to instance-specific data. Here are examples of using staticmethod() function.
Python
class MathUtils:
@staticmethod
def add(a, b):
return a + b
result = MathUtils.add(9, 8)
print(result)
Output
17
Static method() Without Calling Instance
In the code a class with method greet() is created, then it was converted to the static method using staticmethod(), and it is called without creating an instance, as we have discussed earlier it is not required to create an instance of the class to call a static method.
Python
class demoClass:
def greet(msg):
return msg
# convert the greet to a static method
demoClass.greet = staticmethod(demoClass.greet)
# we can access the method without
# creating the instance of class
print(demoClass.greet("Demo class is Today"))
Output
Demo class is Today
Static Method() for Mathematical Operations
If we don’t require to use the class properties then we can use static methods, here in the above code add() method does not use any class properties so it is made static using staticmethod() and the diff method needs to be called by creating an instance because it uses class properties.
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 the add to a static method
demoClass.add = staticmethod(demoClass.add)
# we can access the method without creating
# the instance of class
print(demoClass.add(1, 2))
# if we want to use properties of a class
# then we need to create a object
Object = demoClass(1, 2)
print(Object.diff())
Output
3
-1
Static method() To Access Class variables
Python static method allows you to directly access class variables. Static methods cannot access instance-specific data since they are not tied to any specific instance of the class. They do, however, have access to class-level information, which includes class variables.
Python
class MathUtils:
num = 40
@staticmethod
def double():
return MathUtils.num * 2
result = MathUtils.double()
print(result)
Output
80
Static method() for String Formatting
String formatting operations can be carried out using static methods. Without having access to instance-specific data, they offer a means of encapsulating string formatting logic within a class.
Python
class Formatter:
@staticmethod
def format_name(first_name, last_name):
return f"{last_name}, {first_name}"
formatted_name = Formatter.format_name("For Geeks", "Geeks")
print(formatted_name)
Output
Geeks, For Geeks
Python staticmethod() Function – FAQs
What is the staticmethod function in Python?
The staticmethod function in Python transforms a method into a static method. This means that the method becomes independent of any instance or class variable, effectively treating it as a regular function that happens to reside within a class’s definition. It does not receive an implicit first argument, typically known as self or cls.
How is the @staticmethod decorator used in Python?
The @staticmethod decorator is applied before a method definition within a class to declare that method as a static method. It tells the Python interpreter that this method should not expect an instance (self) or class (cls) as the first parameter. Here’s an example:
class MyClass:
@staticmethod
def my_static_method(arg1, arg2):
return arg1 + arg2
# Usage
result = MyClass.my_static_method(5, 3)
print(result) # Outputs: 8
What is the __new__ staticmethod in Python?
There might be a misunderstanding in the question. __new__ and staticmethod are separate concepts. __new__ is a special method used for creating and returning a new object instance of a class. It’s typically used in advanced scenarios, such as overriding immutable types or controlling object creation. It isn’t inherently related to staticmethod.
Is @staticmethod necessary?
The necessity of @staticmethod depends on the design requirements of your program. If you need a method that neither modifies the class state nor the object state and logically belongs within the class (for organizational or conceptual reasons), then @staticmethod is appropriate. However, if a method doesn’t interact with the class at all, it could alternatively be defined outside of the class as a regular function.
What is the advantage of staticmethod?
The main advantages of using staticmethod include:
- Namespace organization: Static methods keep functions logically organized within the class they pertain to, which can enhance code readability and maintainability.
- Memory efficiency: Since static methods don’t require instance references, they don’t need to be instantiated, potentially saving memory when many instances of a class are created.
- Design clarity: Using
staticmethod can make it clear to future maintainers of the code that a particular method does not alter or depend on the state of the class or its instances.