繁体   English   中英

Python中的装饰器功能

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM