[英]Decorator Functions in Python
The Decorator Function of Python has this simple template Python的Decorator Function具有此简单模板
@A
@B
def C():
It modify the C function to C=A(B(C)); 它将C函数修改为C = A(B(C));
Let's give a more specific example 让我们举一个更具体的例子
@request("POST", "%(channel)d/sequence/%(args)s")
@response("%d")
def outputSequence(self, channel, args):
self.checkDigitalChannelExported(channel)
self.checkPostingValueAllowed()
self.checkDigitalChannel(channel)
(period, sequence) = args.split(",")
period = int(period)
GPIO.outputSequence(channel, period, sequence)
return int(sequence[-1])
So from the above, would the transformed function be 因此,从上面看,转换后的函数是否为
like request(response(outSequence(self, channel, args))? 像request(response(outSequence(self,channel,args))?
Parameterized decorators behave a bit differently. 参数化装饰器的行为略有不同。 The function request
accepts only the arguments, it's a decorator maker : 函数request
仅接受参数,它是装饰器制造商 :
def request(arg1, arg2):
def my_decorator(func):
def wrapper():
#do something
return wrapper
return my_decorator
So the function calls is like: 所以函数调用就像:
decorator = request(arg1, arg2)
response_decorator = decorator(response(arg1, arg2))
outputSequence = response_decorator(outputSequence(self, arg1, arg2))
Here's a tiny example: 这是一个小例子:
>>> def make_decorators(arg1, arg2):
def decorator(func):
def wrapper():
print("We got here!")
return wrapper
return decorator
>>> @make_decorators(1, 2)
def my_func():
pass
>>> my_func()
We got here!
Close. 关。 When a decorator is given one or more arguments, the effect is to call the decorator, which returns a function that is then applied to the function it is decorating. 当给一个装饰器一个或多个参数时,其效果是调用该装饰器,该装饰器返回一个函数,然后将该函数应用于要装饰的函数。 The effect is something more like (as Niklas B. pointed out): 效果更像(如Niklas B.指出的):
request("POST", "%(channel)d/sequence/%(args)s")(
response("%d")(
outputSequence))(self, channel, args)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.