我正在检查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?
返回的}也是如此。在
wrapper
替换修饰函数,因此被视为一个方法。原来的sayYourAge
取了(self, lie)
,新的{因此,当调用
l.sayYouAge(-3)
时,实际上是在调用嵌套函数wrapper
,此时它是一个绑定方法。绑定方法得到传入的self
,并且-3
被分配给参数lie
。wrapper
调用method_to_decorate(self, lie)
,将这些参数传递给原始修饰函数。在请注意,}是硬编码到
self
和{wrapper()
签名中的;它与修饰函数紧密绑定。这些不是从修饰函数中获取的,编写包装器的程序员事先就知道包装后的版本应该有哪些参数。请注意,包装器根本没有与修饰函数匹配参数。在您可以添加参数,例如:
现在你可以用不同的方式让露西谎报她的年龄:
^{pr2}$相关问题 更多 >
编程相关推荐