Skip to main content
 首页 » 编程设计

python之Python 中的装饰器函数

2025年05月04日15JustinYoung

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

那么从上面,转换后的函数是

像请求(响应(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!