Class Decorators
Explore how to write and apply class decorators in Python, learning their benefits like code reuse and interface enforcement. Understand how decorators add methods dynamically, improving code maintainability and reducing boilerplate in complex systems.
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 class is something rather convoluted and that such a scenario might jeopardize ...