如何在python类上创建带有参数的装饰器函数? [英] How to create a decorator function with arguments on python class?

查看:287
本文介绍了如何在python类上创建带有参数的装饰器函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个装饰器函数以对python类进行操作,并能够传递其他参数。我想在实例化类之前 进行操作。这是我的方法:

I want to create a decorator function to operate on a python class, with the ability to pass additional arguments. I want to do that before the class gets instantiated. Here is my approach:

def register(x,a):
    print x,a

@register(5)
class Foo(object):
    pass

,其中 x 是类,而 a 是附加参数。但是我得到

with x being the class and a the additional argument. But I get a

TypeError: register() takes exactly 2 arguments (1 given)

我想要的是某种方式来掌握类 Foo 和其他参数定义类的时间,之前被实例化。

What I want is some way to get hold of the class Foo and additional arguments at the time the class is defined, before the class is instantiated.

推荐答案

您需要这样做:

def makeDeco(a):
    def deco(cls):
        print cls, a
        return cls
    return deco

>>> @makeDeco(3)
... class Foo(object):
...     pass
<class '__main__.Foo'> 3

您可以使用 functools.wraps 和等等来修饰它,但这就是想法。您需要编写一个返回装饰器的函数。外部装饰器制作函数采用 a 参数,而内部装饰器函数采用该类。

You can use functools.wraps and so forth to spruce it up, but that is the idea. You need to write a function that returns a decorator. The outer "decorator-making" function takes the a argument, and the inner decorator function takes the class.

它的工作方式是,当您编写 @makeDeco(3)时,它将调用 makeDeco(3) makeDeco 返回值被用作装饰器。这就是为什么需要 makeDeco 返回要用作装饰器的函数的原因。

The way it works is that when you write @makeDeco(3) it calls makeDeco(3). The return value of makeDeco is what is used as the decorator. That is why you need makeDeco to return the function you want to use as the decorator.

这篇关于如何在python类上创建带有参数的装饰器函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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