Python中的装饰函数

时间:2014-03-06 02:13:39

标签: python

Python的装饰器功能有这个简单的模板

@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])

从上面可以看出,转化后的函数是

like request(response(outSequence(self,channel,args))?

2 个答案:

答案 0 :(得分:5)

参数化装饰器的行为略有不同。函数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!

答案 1 :(得分:2)

关闭。当一个装饰器被赋予一个或多个参数时,效果是调用装饰器,它返回一个函数,然后将该函数应用于它正在装饰的函数。效果更像是(正如Niklas B.指出的那样):

request("POST", "%(channel)d/sequence/%(args)s")(
   response("%d")(
       outputSequence))(self, channel, args)