Menu Close

How to use property() on classmethods with Python?

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.

Posted in Python, Python Answers