python - Python 中的装饰器函数

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

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

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

关于python - Python 中的装饰器函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22213500/

相关文章:

python - wxPython:更改标题的颜色

python - 为什么Basemap南极立体 map 投影坐标与同一投影下的数据集坐标不一致?

python - 无法在 OS X 上使用 python 2.6 让 web.py session 正常工作

jquery - 将 jQuery 图表转换为 PDF

python - Firestore 属性错误 : module 'firebase_admin' has no attribute 'firestore'

python - PyQt5 QtSql 在 QThread 中访问数据库

python - 如何在 Python 中从 VBA 发送/读取数据?

python - ARP扫描程序

python - 如何使用 Django 和 Python 正确格式化日期时间

python - 在 django 项目中生成此日志文件结构所需的建议