Python Glossary Русский

all Python 3OOPterm

@staticmethod

methods

A static method. It takes neither self nor cls. Just a function inside the class — a logical grouping.

Syntax

@staticmethod
def method(...): ...

Unlike classmethod, a static method receives neither the instance nor the class, so it can't reach object or class state. The only reason to keep it inside the class rather than write a plain function is that it logically belongs to the class namespace; if you need the class (say, for a factory), use classmethod instead.

Examples

class MathUtils:
    @staticmethod
    def add(a, b):
        return a + b
    @staticmethod
    def multiply(a, b):
        return a * b
print(MathUtils.add(3, 4))       # → 7
print(MathUtils.multiply(3, 4))  # → 12
class Validator:
    @staticmethod
    def is_email(s):
        return '@' in s and '.' in s.split('@')[-1]
print(Validator.is_email('user@example.com'))  # → True
print(Validator.is_email('not-an-email'))       # → False
class Temperature:
    @staticmethod
    def celsius_to_fahrenheit(c):
        return c * 9/5 + 32
    @staticmethod
    def fahrenheit_to_celsius(f):
        return (f - 32) * 5/9
print(Temperature.celsius_to_fahrenheit(0))  # → 32.0
# Вызов через экземпляр
v = Validator()
print(v.is_email('a@b.com'))  # → True
class StringUtils:
    @staticmethod
    def is_palindrome(s):
        s = s.lower().replace(' ', '')
        return s == s[::-1]
print(StringUtils.is_palindrome('racecar'))  # → True
print(StringUtils.is_palindrome('hello'))    # → False

See also

Open in the full glossarydocs.python.orgReport an inaccuracy