Decorator and closures

眉间皱痕 提交于 2020-01-01 22:15:51

问题


I am going through the How to make a chain of function decorators? to understand decorator.

In the following example, we see that "method_to_decorate" is accessible to wrapper function because of closures. But, I didn't understand how arguments self and lie are accessible to the wrapper function.

def method_friendly_decorator(method_to_decorate):
     def wrapper(self, lie):
         lie = lie - 3 # very friendly, decrease age even more :-)
         return method_to_decorate(self, lie)
     return wrapper

class Lucy(object):

    def __init__(self):
        self.age = 32

    @method_friendly_decorator
    def sayYourAge(self, lie):
        print "I am %s, what did you think?" % (self.age + lie)

l = Lucy()
l.sayYourAge(-3)
#outputs: I am 26, what did you think?

回答1:


The returned wrapper replaces the decorated function, and is thus treated as a method. The original sayYourAge took (self, lie) and so does the new wrapper.

So, when calling l.sayYouAge(-3) you are really calling the nested function wrapper, which is by that time a bound method. Bound methods get self passed in, and -3 is assigned to the argument lie. wrapper calls method_to_decorate(self, lie), passing these arguments on to the original decorated function.

Note that self and lie are hardcoded into the wrapper() signature; it is tightly bound to the decorated function. These were not taken from the decorated function, the programmer who wrote the wrapper knew beforehand what arguments would be expected of the wrapped version. Note that the wrapper doesn't have to match arguments with the decorated function at all.

You could add arguments, for example:

def method_friendly_decorator(method_to_decorate):
     def wrapper(self, lie, offset=-3):
         lie += offset # very friendly, adjust age even more!
         return method_to_decorate(self, lie)
     return wrapper

Now you can make Lucy lie about her age in different ways:

l.sayYourAge(-1, offset=1)  # will say "I am 32, what did you think?"


来源:https://stackoverflow.com/questions/14276839/decorator-and-closures

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!