Yandex

Python staticmethod() Function – Create Static Methods in Classes



Python staticmethod() Function

The staticmethod() function in Python is used to define a static method inside a class. A static method doesn't take the instance (self) or class (cls) as the first argument. It behaves like a regular function but belongs to the class’s namespace.

Syntax

staticmethod(function)

Parameter:

  • function – A function you want to convert into a static method.

Returns:

  • A static method object that can be called on the class or its instances.

Example: Creating a Static Method

class MathUtils:
    @staticmethod
    def add(a, b):
        return a + b

# Call without creating an object
print(MathUtils.add(5, 3))
8

Example: Without Decorator

You can also use staticmethod() without the @staticmethod decorator:

class MathUtils:
    def add(a, b):
        return a + b

    add = staticmethod(add)

print(MathUtils.add(10, 4))
14

Use Case: When to Use staticmethod()?

  • When the method doesn’t need access to the instance or class.
  • Utility functions that logically belong to the class, but don’t use class or instance data.

Comparison: staticmethod vs classmethod

Featurestaticmethod()classmethod()
Access to instance?NoNo
Access to class?NoYes
First argumentNonecls
Use caseHelper functionsFactory methods

Common Mistakes

  • Trying to use self or cls inside a static method – it won’t work.
  • Not using @staticmethod decorator or staticmethod() function – method acts as a normal one and expects self.

Interview Tip

Interviewers often ask the difference between staticmethod() and classmethod(). Know when and why to use each.

Summary

  • staticmethod() makes a function callable via the class without needing an object.
  • It doesn’t access or modify class or instance state.
  • Perfect for utility/helper methods inside a class.

Practice Problem

Create a class Temperature with a static method celsius_to_fahrenheit(c) that converts Celsius to Fahrenheit.

class Temperature:
    @staticmethod
    def celsius_to_fahrenheit(c):
        return (c * 9/5) + 32

print(Temperature.celsius_to_fahrenheit(37))

Expected Output:

98.6


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M