Python中的装饰函数

lil*_*lzz 1 python

Python的Decorator函数有这个简单的模板

@A

@B

def C():
Run Code Online (Sandbox Code Playgroud)

它将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])
Run Code Online (Sandbox Code Playgroud)

所以从上面来看,转换后的函数是否可以

喜欢请求(响应(outSequence(self,channel,args))?

aIK*_*Kid 5

参数化装饰器的行为略有不同.该函数request只接受参数,它是一个装饰器制造商:

def request(arg1, arg2):
    def my_decorator(func):
        def wrapper():
           #do something
        return wrapper
    return my_decorator
Run Code Online (Sandbox Code Playgroud)

所以函数调用就像:

decorator = request(arg1, arg2)
response_decorator = decorator(response(arg1, arg2))
outputSequence = response_decorator(outputSequence(self, arg1, arg2))
Run Code Online (Sandbox Code Playgroud)

这是一个很小的例子:

>>> 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!
Run Code Online (Sandbox Code Playgroud)