已读94%
预计阅读本页时间:-
预计阅读本页时间:-
Test Your Knowledge: Quiz
- As mentioned in one of this chapter’s Notes, the timer function decorator with decorator arguments that we wrote in the section Adding Decorator Arguments can be applied only to simple functions, because it uses a nested class with a __call__ operator overloading method to catch calls. This structure does not work for class methods because the decorator instance is passed to self, not the subject class instance. Rewrite this decorator so that it can be applied to both simple functions and class methods, and test it on both functions and methods. (Hint: see the section Class Blunders I: Decorating Class Methods for pointers.) Note that you may make use of assigning function object attributes to keep track of total time, since you won’t have a nested class for state retention and can’t access nonlocals from outside the decorator code.
- The Public/Private class decorators we wrote in this chapter will add overhead to every attribute fetch in a decorated class. Although we could simply delete the @ decoration line to gain speed, we could also augment the decorator itself to check the __debug__ switch and perform no wrapping at all when the –O Python flag is passed on the command line (just as we did for the argument range-test decorators). That way, we can speed our program without changing its source, via command-line arguments (python –O main.py...). Code and test this extension.