装饰和封闭

2024-04-26 17:57:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在检查How to make a chain of function decorators? 了解装修师。在

在下面的示例中,我们看到由于闭包,包装函数可以访问“method_to_decorate”。 但是,我不明白包装器函数如何访问参数self和{}。在

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?

Tags: to函数selfagereturndefdecoratorwrapper
1条回答
网友
1楼 · 发布于 2024-04-26 17:57:16

返回的wrapper替换修饰函数,因此被视为一个方法。原来的sayYourAge取了(self, lie),新的{}也是如此。在

因此,当调用l.sayYouAge(-3)时,实际上是在调用嵌套函数wrapper,此时它是一个绑定方法。绑定方法得到传入的self,并且-3被分配给参数liewrapper调用method_to_decorate(self, lie),将这些参数传递给原始修饰函数。在

请注意,self和{}是硬编码到wrapper()签名中的;它与修饰函数紧密绑定。这些不是从修饰函数中获取的,编写包装器的程序员事先就知道包装后的版本应该有哪些参数。请注意,包装器根本没有与修饰函数匹配参数。在

您可以添加参数,例如:

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

现在你可以用不同的方式让露西谎报她的年龄:

^{pr2}$

相关问题 更多 >