预计阅读本页时间:-
Managing Functions and Classes
Although most examples in this chapter deal with using wrappers to intercept later calls to functions and classes, this is not the only way decorators can be used:
广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元
- Function decorators can also be used to manage function objects, instead of later calls to them—to register a function to an API, for instance. Our primary focus here, though, will be on their more commonly used call wrapper application.
- Class decorators can also be used to manage class objects directly, instead of instance creation calls—to augment a class with new methods, for example. Because this role intersects strongly with that of metaclasses (indeed, both run at the end of the class creation process), we’ll see additional use cases in the next chapter.
In other words, function decorators can be used to manage both function calls and function objects, and class decorators can be used to manage both class instances and classes themselves. By returning the decorated object itself instead of a wrapper, decorators become a simple post-creation step for functions and classes.
Regardless of the role they play, decorators provide a convenient and explicit way to code tools useful both during program development and in live production systems.