Compared to decorators applied to a function, it’s not easy to understand the decorators applied to a class.
@foo
class Bar(object):
def __init__(self, x):
self.x = x
def spam(self):
statements
What’s the use case of decorators to a class? How to use it?
It replaces the vast majority of classic good uses for custom metaclasses in a much simpler way.
Think about it this way: nothing that’s directly in the class body can refer to the class object, because the class object doesn’t exist until well after the body’s done running (it’s the metaclass’s job to create the class object — usually
type‘s, for all classes without a custom metaclass).But, the code in the class decorator runs after the class object is created (indeed, with the class object as an argument!) and so can perfectly well refer to that class object (and usually needs to do so).
For example, consider:
and now you can refer to
Color.red,Color.green, &c, rather than to0,1, etc. (Of course you normally would add even more functionality to make “anenum“, but here I’m just showing the simple way to put such functionality addition in a class decorator, rather than needing a custom metaclass!-)