带有选项的Python装饰器 [英] Python decorator with options

查看:101
本文介绍了带有选项的Python装饰器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模块,该模块的功能原型类似于线程类.

I have a module that has a function whose prototype is similar to that of the thread class.

def do(fn, argtuple=(), kwargdict={}, priority=0,
            block=False, timeout=0, callback=None, daemon=False)

    # do stuff

fn是可调用的,而argtuple和kwargdict是位置参数和字典参数,它们在被调用时将传递给fn可调用的对象.

fn is a callable, and argtuple and kwargdict are positional and dictionary arguments that will be passed to the fn callable when it gets called.

我现在正试图为此编写一个装饰器,但是我很困惑.我从来没有真正了解装饰器.有没有办法制作一个装饰器,使我可以在上面设置超时等选项,但是在调用该函数时传入argtuple和kwargdict.

I'm now trying to write a decorator for this, but I'm confused. I've never really had a very good grasp on decorators. Is there a way to make a decorator that I can set the options in the above such as timeout, but pass in argtuple and kwargdict when the function is called.

例如:

@do(priority=2)
def decoratedTask(arg, dic=3):
    #do stuff

decoratedTask(72)

我很困惑如何将运行时参数72传递给装饰函数.我认为装饰器必须是__call__方法返回函数调用的类,但是我不确定如何传递这样的参数的语法.

I'm confused how I would pass the runtime argument 72 into the decorated function. I'm thinking the decorator needs to be a class where the __call__ method returns the function call, but I'm unsure the syntax of how to pass in arguments like that.

这有意义吗?

推荐答案

装饰器的作用是将函数作为参数并返回一个函数,通常是在装饰器中创建的新函数.

What the decorator does is that it takes the function as an argument and also returns a function, typically a new function that is created in the decorator.

该新函数需要使用与装饰的函数相同的参数,并且还需要调用原始函数.

That new function needs to take the same parameters as the function you decorate, and it also needs to call the original function.

现在,当您有一个带有参数的装饰器时,将进行额外的处理.该装饰器应接受参数,然后返回装饰器.实际上,您使用的功能不是装饰器,而是装饰器!

Now, when you have a decorator with an argument, there is an extra level going on. That decorator should take the argument, and return a decorator. The function you use is in fact not a decorator, but a decoratormaker!

这里是一个例子:

>>> def mydeco(count):
...     def multipass(fn):
...         def caller(*args, **kw):
...             return [fn(*args, **kw) for x in range(count)]
...         return caller
...     return multipass
... 
>>> @mydeco(5)
... def printer(text):
...     print(text)
... 
>>> printer("Yabbadabbadoo!")
Yabbadabbadoo!
Yabbadabbadoo!
Yabbadabbadoo!
Yabbadabbadoo!
Yabbadabbadoo!
[None, None, None, None, None]

您将看到这些装饰器制造商的示例实现为类.我也喜欢它(尽管我通常总是最终根本没有装饰器),但是函数中的函数起作用了. :)

You'll see examples of these decoratormakers implemented as classes. That how I prefer it too (although I usually end up not having a decorator at all anyway), but a function in a function in a function works. :)

这篇关于带有选项的Python装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆