Is it possible to have static methods in Python so I can call them without initializing a class, like:
ClassName.StaticMethod ( )
Is it possible to have static methods in Python so I can call them without initializing a class, like:
ClassName.StaticMethod ( )
Perhaps the simplest option is just to put those functions outside of the class:
Using this method, functions which modify or use internal object state (have side effects) can be kept in the class, and the reusable utility functions can be moved outside.
Let's say this file is called
dogs.py
. To use these, you'd calldogs.barking_sound()
instead ofdogs.Dog.barking_sound
.If you really need a static method to be part of the class, you can use the staticmethod decorator.
I encounter this question from time to time. The use case and example that I am fond of is:
It does not make sense to create an object of class cmath, because there is no state in a cmath object. However, cmath is a collection of methods that are all related in some way. In my example above, all of the functions in cmath act on complex numbers in some way.
Yes, static methods can be created like this (although it's a bit more Pythonic to use underscores instead of CamelCase for methods):
The above uses the decorator syntax. This syntax is equivalent to
This can be used just as you described:
A builtin example of a static method is
str.maketrans()
in Python 3, which was a function in thestring
module in Python 2.Another option that can be used as you describe is the
classmethod
, the difference is that the classmethod gets the class as an implicit first argument, and if subclassed, then it gets the subclass as the implicit first argument.Note that
cls
is not a required name for the first argument, but most experienced Python coders will consider it badly done if you use anything else.These are typically used as alternative constructors.
A builtin example is
dict.fromkeys()
:Yes, check out the staticmethod decorator:
Yep, using the staticmethod decorator
Note that some code might use the old method of defining a static method, using
staticmethod
as a function rather than a decorator. This should only be used if you have to support ancient versions of Python (2.2 and 2.3)This is entirely identical to the first example (using
@staticmethod
), just not using the nice decorator syntaxFinally, use
staticmethod()
sparingly! There are very few situations where static-methods are necessary in Python, and I've seen them used many times where a separate "top-level" function would have been clearer.The following is verbatim from the documentation::
Python Static methods can be created in two ways.
Using staticmethod()
Output:
Result: 25
Using @staticmethod
Output:
Result: 25