Sometimes, we want to add static methods in Python classes.
In this article, we’ll look at how to add static methods in Python classes.
How to add static methods in Python classes?
To add static methods in Python classes, we use the @staticmethod
decorator.
For instance, we write:
class C:
@staticmethod
def f():
print('static')
C.f()
We make f
a static method with the @staticmethod
decorator.
Then we call C.f
dirertly without instantiating C
.
Therefore, we see 'static'
printed.
Conclusion
To add static methods in Python classes, we use the @staticmethod
decorator.