Python Reference ยท Built-in Functions
Python staticmethod() function
Reference for Python staticmethod() and the @staticmethod decorator: methods without self or cls, when to use them, and how they differ from classmethod.
staticmethod() is a built-in that wraps a function so it can live inside a class but receives neither the instance nor the class as an automatic first argument. You almost always use it as the decorator @staticmethod.
A static method is an ordinary function that happens to be grouped with a class because it is conceptually related: a validator, a parser, a small helper. It can be called on the class or on an instance, with the same result.
class Math: @staticmethod def square(n): return n * n Math.square(4) # 16
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
class C: @staticmethod def f(arg1, arg2): ... # or, without decorator syntax f = staticmethod(function)
| Name | Description |
|---|---|
function |
The function to wrap. |
Return value: a staticmethod descriptor object. Accessing it through the class or an instance returns the plain underlying function.
Usage notes
- No
self, nocls. A static method cannot read instance attributes or class attributes unless you name the class explicitly (Temperature.LIMIT), which also ignores subclasses. - Need the class? Use
classmethod(), which receivesclsand works with inheritance, as in alternative constructors. - Need the instance? Write a normal method.
- Not a requirement. If a helper has nothing to do with a class, a module-level function is often simpler and equally Pythonic.
- Inheritance. Subclasses inherit static methods and can override them, but calls never receive the subclass automatically.
- Calling on the instance works but suggests the method uses the instance; prefer
ClassName.method()for clarity. - Since Python 3.10 a static method is itself callable and gets
__wrapped__, so it can be used directly as a regular function inside the class body. - Common mistake: forgetting the decorator and omitting
self, which makesinstance.method()pass the instance as an unexpected argument and raiseTypeError.
Related
classmethod(),property(),super(),object()- Lessons: Methods, Classes, Decorators