Categories
Python Answers

How to add static methods in Python classes?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *