ZetCode

Python static methods

last modified November 29, 2026 Python 3.15

In this article we show how to define and use static methods in Python.

A static method is a function defined in a class body and marked with the @staticmethod decorator. Unlike an ordinary method, it receives no automatic first argument: neither the instance (self) nor the class (cls). It works only with the arguments passed to it. A static method is placed in a class because it belongs to the class logically, for example a conversion or validation rule, not because it needs the class or instance data.

Instance methods and class methods are introduced in Python methods. This article looks at static methods in detail and compares them with the other two kinds.

Defining a static method

A static method is defined with the @staticmethod decorator placed on the line before def. Its parameters are only the values it works with.

first_static.py
class Units:

    @staticmethod
    def km_to_miles(km):
        return km * 0.621371

    @staticmethod
    def miles_to_km(miles):
        return miles / 0.621371


print(Units.km_to_miles(42.195))
print(Units.miles_to_km(26.2))

The Units class groups two conversion functions. They are called on the class itself; no object of the class is created. The methods do not have a self parameter, because they do not use any object state.

$ python first_static.py
26.218749345
42.164825844785156

Calling on instances and from other classes

A static method can also be called on an instance. The instance is used only to find the method; it is not passed as an argument.

instance_call.py
class Units:

    @staticmethod
    def km_to_miles(km):
        return km * 0.621371


class Trip:

    def __init__(self, name, km):
        self.name = name
        self.km = km

    def describe(self):
        miles = Units.km_to_miles(self.km)
        return f"{self.name}: {self.km} km ({miles:.1f} miles)"


u = Units()
print(u.km_to_miles(10))

trip = Trip("Bratislava-Vienna", 79)
print(trip.describe())

u.km_to_miles(10) receives only the number 10. The describe method of the Trip class uses the conversion through the class name. A static method is an ordinary function reachable through the class, so any code that can see the class can call it.

$ python instance_call.py
6.21371
Bratislava-Vienna: 79 km (49.1 miles)

Without the decorator

A function in a class body without the decorator is an ordinary method. Calling it on the class works, because no instance is involved, but calling it on an instance passes the instance as the first argument.

no_decorator.py
class Units:

    def km_to_miles(km):
        return km * 0.621371


print(Units.km_to_miles(10))

u = Units()
print(u.km_to_miles(10))

Units.km_to_miles(10) works. u.km_to_miles(10) is turned into Units.km_to_miles(u, 10), which gives the function two arguments while it accepts only one. The @staticmethod decorator switches this binding off.

$ python no_decorator.py
6.21371
Traceback (most recent call last):
  File "/home/user/static-methods/no_decorator.py", line 10, in <module>
    print(u.km_to_miles(10))
          ~~~~~~~~~~~~~^^^^
TypeError: Units.km_to_miles() takes 1 positional argument but 2 were given

Helper methods

Static methods are often used for helper logic that other methods of the class share, such as validation. Instance methods can call them through self or through the class name.

helpers.py
class Order:

    def __init__(self, product, quantity):
        if not self.valid_quantity(quantity):
            raise ValueError(f"invalid quantity: {quantity}")
        self.product = product
        self.quantity = quantity

    @staticmethod
    def valid_quantity(quantity):
        return isinstance(quantity, int) and 1 <= quantity <= 100

    def change(self, quantity):
        if not Order.valid_quantity(quantity):
            print("rejected:", quantity)
            return
        self.quantity = quantity
        print("changed to", quantity)


order = Order("paper", 5)
order.change(250)
order.change(20)
print(Order.valid_quantity(0), Order.valid_quantity(3))

try:
    Order("ink", -1)
except ValueError as e:
    print("error:", e)

valid_quantity checks that a quantity is an integer between 1 and 100. The constructor calls it through self and raises a ValueError for invalid values; change calls it through the class name and rejects bad values. Code outside the class can use the same rule, for example to validate form input before an order is created.

$ python helpers.py
rejected: 250
changed to 20
False True
error: invalid quantity: -1

Static methods versus class methods

A factory method that creates objects should usually be a class method. A static method has no access to the class it was called on, so it must name a class explicitly, and subclasses inherit that fixed choice.

static_vs_class.py
class Point:

    def __init__(self, x, y):
        self.x = x
        self.y = y

    @staticmethod
    def origin_static():
        return Point(0, 0)

    @classmethod
    def origin(cls):
        return cls(0, 0)

    def show(self):
        return f"{type(self).__name__}({self.x}, {self.y})"


class Point3D(Point):

    def __init__(self, x, y, z=0):
        super().__init__(x, y)
        self.z = z


print(Point.origin_static().show())
print(Point3D.origin_static().show())
print(Point3D.origin().show())

origin_static always creates a Point, even when it is called on Point3D. The class method origin receives the class it was called on in cls and creates a Point3D. A rule of thumb: use an instance method when the code needs the object, a class method when it needs the class, and a static method when it needs neither.

$ python static_vs_class.py
Point(0, 0)
Point(0, 0)
Point3D(0, 0)

Overriding static methods

A subclass can define a static method with the same name and replace the inherited one. Which version runs depends on how the method is called: through self, the lookup starts at the class of the object; through the base class name, it is fixed.

overriding.py
class Shipping:

    def __init__(self, weight):
        self.weight = weight

    @staticmethod
    def rate(weight):
        return 5 + weight * 1.5

    def cost(self):
        return self.rate(self.weight)

    def cost_fixed(self):
        return Shipping.rate(self.weight)


class Express(Shipping):

    @staticmethod
    def rate(weight):
        return 15 + weight * 2.5


for parcel in [Shipping(4), Express(4)]:
    name = type(parcel).__name__
    print(name, parcel.cost(), parcel.cost_fixed())

Express overrides the rate rule. cost calls self.rate, so an express parcel uses the express rate. cost_fixed names Shipping directly and ignores the override. Calling static methods through self or type(self) keeps them overridable.

$ python overriding.py
Shipping 11.0 11.0
Express 25.0 11.0

The staticmethod object

The decorator wraps the function in a staticmethod object, which is stored in the class dictionary. Accessing it through the class or an instance returns the plain function. Since Python 3.10, the wrapper can also be called directly, for example in the class body.

staticmethod_object.py
class Text:

    @staticmethod
    def normalize(word):
        return word.strip().lower()

    def shout(word):
        return word.upper() + "!"

    shout_upper = staticmethod(shout)
    STOP = normalize("  THE ")


print(type(Text.__dict__["normalize"]).__name__)
print(type(Text.normalize).__name__)
print(Text.normalize is Text.__dict__["normalize"].__func__)

print(Text.STOP)
print(Text().shout_upper("stop"))

The class dictionary holds a staticmethod object, while Text.normalize is the original function, available as the __func__ attribute of the wrapper. The decorator is only a shorter form of calling staticmethod on a function, as shout_upper = staticmethod(shout) shows. STOP is computed in the class body by calling normalize while the class is being created. The plain shout function remains in the class as an ordinary method; it is shown here only as the input of staticmethod.

$ python staticmethod_object.py
staticmethod
function
True
the
STOP!

Static methods as functions

Because a static method accessed through the class is a plain function, it can be passed wherever a function is expected, for example as the key argument of sorted or to map.

as_key.py
class Text:

    @staticmethod
    def normalize(word):
        return word.strip().lower()

    @staticmethod
    def vowel_count(word):
        return sum(1 for ch in word.lower() if ch in "aeiou")


words = ["  Pear", "apple ", "Banana", "cherry"]

print(sorted(words))
print(sorted(words, key=Text.normalize))
print(sorted(words, key=Text.vowel_count))

print(list(map(Text.normalize, words)))

Plain sorted orders the strings by code points, so the leading spaces and the capital letters decide the order. Text.normalize as the key sorts them alphabetically while keeping the original strings. Text.vowel_count sorts by the number of vowels; words with equal counts keep their original order. map applies normalize to every word. Sorting is covered in Python sort list.

$ python as_key.py
['  Pear', 'Banana', 'apple ', 'cherry']
['apple ', 'Banana', 'cherry', '  Pear']
['cherry', '  Pear', 'apple ', 'Banana']
['pear', 'apple', 'banana', 'cherry']

Source

staticmethod, classmethod, Descriptor guide: static methods

In this article we have defined static methods with the staticmethod decorator, called them on classes and instances, seen what happens without the decorator, used them as helpers, compared them with class methods, overridden them in subclasses, looked at the staticmethod object, and passed static methods as functions. A static method is not always necessary: a function at the module level does the same job when it does not belong to a particular class. See also Python methods, Python property decorator, and Python decorators.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.