staticmethod()

The built-in staticmethod() function is a decorator that lets you transform a method into a static method. Static methods don’t receive an implicit first argument. They don’t have access to the instance (self) or class (cls) objects. Instead, they behave like regular functions defined within a class:

Python
>>> class DemoClass:
...     @staticmethod
...     def static_method():
...         return "Hello from static method!"

>>> DemoClass.static_method()
'Hello from static method!'

staticmethod() Syntax

Python Syntax
@staticmethod
def method(*args, **kwargs):
    ...

Arguments

Argument Description
method The method to be transformed into a static method

Return Value

  • Returns a static method object that can be called on a class or its instances.

staticmethod() Examples

With a function to be transformed into a static method:

Python
>>> class Greeter:
...     @staticmethod
...     def greet(name):
...         return f"Hello, {name}!"
...

>>> Greeter.greet("Pythonista")
'Hello, Pythonista!'

With an instance of the class:

Python
>>> instance = Greeter()
>>> instance.greet("Developer")
'Hello, Developer!'

staticmethod() Common Use Cases

The most common use cases for the staticmethod() function include:

  • Grouping utility functions within a class
  • Providing a function that doesn’t need access to class or instance data
  • Creating a namespace for related functions

staticmethod() Real-World Example

Consider a Formatter class that provides methods to format numbers as currency and percentages. These methods don’t rely on instance or class data, so they can be defined as static methods:

Python formatter.py
class Formatter:
    @staticmethod
    def as_currency(value):
        return f"${value:,.2f}"

    @staticmethod
    def as_percent(value):
        return f"{value:.2%}"

# Usage
formatter = Formatter()
print(formatter.as_currency(1000))  # Output: $1,000.00
print(formatter.as_percent(0.25))  # Output: 25.00%

In this example, .as_currency() and .as_percent() are static methods that format numbers without needing access to any instance or class variables. This helps in logically grouping utility functions within the Formatter class.

Tutorial

Python's Instance, Class, and Static Methods Demystified

This tutorial helps demystify what's behind class, static, and instance methods in Python.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Nov. 14, 2024 • Reviewed by Dan Bader