Categories
Python Answers

How to use property() on classmethods with Python?

Spread the love

Sometimes, we want to use property() on classmethods with Python.

In this article, we’ll look at how to use property() on classmethods with Python.

How to use property() on classmethods with Python?

To use property() on classmethods with Python, we can just use them together.

For instance, we write

class G:
    @classmethod
    @property
    def __doc__(cls):
        return f'A doc for {cls.__name__!r}'

to call both the classmethod and property decorators on the __doc__ method in class G.

Then we can access the cls class in it.

This works since Python 3.9.

The order of the decorators has to be the same as listed.

Conclusion

To use property() on classmethods with Python, we can just use them together.

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 *