Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
So far we’ve been coding function decorators to manage function calls, but as we’ve seen, Python 2.6 and 3.0 extend decorators to work on classes too. As described earlier, while similar in concept to function decorators, class decorators are applied to classes instead—they may be used either to manage classes themselves, or to intercept instance creation calls in order to manage instances. Also like function decorators, class decorators are really just optional syntactic sugar, though many believe that they make a programmer’s intent more obvious and minimize erroneous calls.
Because class decorators may intercept instance creation
calls, they can be used to either manage all the instances of a
class, or augment the interfaces of those instances. To demonstrate,
here’s a first class decorator example that does the former—managing
all instances of a class. This code implements the classic
singleton coding pattern, where at most one
instance of a class ever exists. Its singleton function defines and returns a
function for managing instances, and the @ syntax automatically wraps up a subject
class in this function: