[英]Decorator Functions in Python
Python的Decorator Function具有此簡單模板
@A
@B
def C():
它將C函數修改為C = A(B(C));
讓我們舉一個更具體的例子
@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])
因此,從上面看,轉換后的函數是否為
像request(response(outSequence(self,channel,args))?
參數化裝飾器的行為略有不同。 函數request
僅接受參數,它是裝飾器制造商 :
def request(arg1, arg2):
def my_decorator(func):
def wrapper():
#do something
return wrapper
return my_decorator
所以函數調用就像:
decorator = request(arg1, arg2)
response_decorator = decorator(response(arg1, arg2))
outputSequence = response_decorator(outputSequence(self, arg1, arg2))
這是一個小例子:
>>> 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!
關。 當給一個裝飾器一個或多個參數時,其效果是調用該裝飾器,該裝飾器返回一個函數,然后將該函數應用於要裝飾的函數。 效果更像(如Niklas B.指出的):
request("POST", "%(channel)d/sequence/%(args)s")(
response("%d")(
outputSequence))(self, channel, args)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.