Class Decorators

Learn how to write decorators utilizing classes in Python.

Classes are also objects in Python (frankly, pretty much everything is an object in Python, and it's hard to find a counter-example; however, there are some technical nuances). That means the same considerations apply; they can also be passed by parameters, assigned to variables, asked some methods, or be transformed (decorated).

The difference between class and function decorators

Class decorators were introduced in PEP-3129, and they have very similar considerations to the function decorators we just explored. The only difference is that when writing the code for this kind of decorator, we have to take into consideration that we are receiving a class as a parameter of the wrapped method, not another function.

Writing class decorators

We saw how to use a class decorator when we saw the dataclasses.dataclass decorator in an earlier lesson (Creating Classes with a More Compact Syntax). Now, we'll learn how to write our own class decorators.

Some practitioners might argue that decorating a ...

Get hands-on with 1400+ tech skills courses.