@staticmethod

A method that gets neither the object nor the class automatically. It behaves like a plain function placed inside a class.

On this page

Example

#
Python
class Grade:
    def __init__(self, points):
        if not Grade.is_valid(points):
            raise ValueError("Points must be between 0 and 100")
        self.points = points

    @staticmethod
    def is_valid(points):
        return 0 <= points <= 100

    @staticmethod
    def to_percent(points, maximum):
        return round(points / maximum * 100)

print(Grade.is_valid(85), Grade.is_valid(120))
print(Grade.to_percent(18, 24))
print(list(filter(Grade.is_valid, [85, 120, -5, 64])))
print(Grade(72).is_valid(50))
Resultsaved result, you can check it
True False
75
[85, 64]
True

Definition and usage

#

The @staticmethod decorator creates a static method: a function that belongs to the class but does not automatically receive any first argument. It has neither self nor cls, so it also has no access to the object’s or the class’s attributes, unless you pass them in explicitly.

You call a static method through the class (Grade.is_valid(72)) or through an object, and the result depends only on the arguments. It is used for helper functions that logically belong to the class, for example validation or a calculation, but do not need its data. Placing them in the class groups related code together and makes it easier to find.

If a helper function is not tied to any class, it is usually better to leave it as a plain function in the module. When a method needs to create objects of the class or use class attributes, you need @classmethod instead.

Syntax

#
Syntax
class Name:
    @staticmethod
    def method(args):
        ...

Name.method(args)

More examples

#
Three kinds of methods in one class
Python
class Course:
    count = 0

    def __init__(self, title):
        self.title = title
        Course.count += 1

    def describe(self):
        return f"Course {self.title}"

    @classmethod
    def total(cls):
        return f"Courses: {cls.count}"

    @staticmethod
    def slugify(title):
        return title.lower().replace(" ", "-")

python = Course("Python from scratch")
print(python.describe())
print(Course.total())
print(Course.slugify("Python from scratch"))
Resultsaved result, you can check it
Course Python from scratch
Courses: 1
python-from-scratch

An ordinary method gets the object (self), a class method gets the class (cls), and a static method gets only what you pass it.

Good practices

#
  • If a method does not use self, consider whether it should be static, or not in the class at all.
  • Call a static method through the class name rather than an object. It immediately shows that it does not depend on any object’s state.
  • Static methods are easy to test, because their result depends only on the arguments.

Related entries

#

Spotted a mistake or missing an example? Write to us.