The Wayback Machine - https://web.archive.org/web/20250311064236/https://www.geeksforgeeks.org/python-staticmethod-function/
Open In App

Python staticmethod() Function

Last Updated : 03 Mar, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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"))

Output
Hello, 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)

Output
17

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())

Output
3
-1

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)

Output
80

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)

Output
Geeks, For Geeks

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"))

Output
Hello, 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).

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.


Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg