Define a static method in Python

Use staticmethod for class-related helpers, distinguish automatic instance and class binding, and choose classmethod when subclass-aware state matters.

Best practices
Python programming and application logging

Decorate a method with @staticmethod when it belongs with a class conceptually but does not need an automatically supplied instance or class argument. It receives only the arguments you explicitly pass.

Define and call it

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

print(MathUtils.add(2, 3))    # 5
print(MathUtils().add(2, 3))  # 5

Calling through the class usually makes a stateless helper's role clearest. Calling through an instance is also valid and does not insert that instance into the argument list.

Compare method binding

Method kind Automatically supplied argument Typical role
Instance method The instance, conventionally self Read or change object state
Class method The class, conventionally cls Alternative constructors or subclass-aware behavior
Static method None A helper grouped with the class
class Demo:
    class_attr = "shared"

    def __init__(self):
        self.attr = "instance"

    def instance_method(self):
        return self.attr

    @classmethod
    def class_method(cls):
        return cls.class_attr

    @staticmethod
    def static_method(value):
        return value.upper()

Static methods are not forbidden from accessing other objects or class attributes. They simply receive no automatic self or cls. Referring to Demo.class_attr works, but hard-codes that class rather than following a subclass supplied as cls.

Group a parsing helper with a class

from datetime import datetime

class DateHelper:
    @staticmethod
    def is_valid_date(text):
        try:
            datetime.strptime(text, "%Y-%m-%d")
        except ValueError:
            return False
        return True

This helper expects a string and tests whether strptime can parse it as a date. It does not enforce a strict ten-character lexical format; some non-zero-padded components can parse. Add format validation if exact representation matters. A wrong input type can raise TypeError rather than returning false.

FAQ

Why not use a module function? That is often equally appropriate. A static method is an organizational choice, not a special runtime capability.

When should I use classmethod instead? Use it when the operation needs the class, especially cls(...) for an alternative constructor that should return a subclass instance.

Can a static method mutate an object? Yes, if an object is passed explicitly or otherwise available. Static binding does not make a function pure or read-only.

References

Get a tailored plan

Contact us

Join the community

Scan with WeChat
to join the community

Try Guance

Start online and pay only for what you use.

Get started

Choose a Guance plan

Code hosting