python decorator参数

时间:2013-03-02 06:31:34

标签: python python-2.7 python-decorators

python decorator函数支持参数如何实现

def decorator(fn, decorArg):
    print "I'm decorating!"
    print decorArg
    return fn

class MyClass(object):
    def __init__(self):
        self.list = []

    @decorator
    def my_function(self, funcArg = None):
        print "Hi"
        print funcArg

在运行中我收到此错误

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

我试过@decorator(arg)或@ decorator arg。它没有用。到目前为止,我想知道这是否可能

1 个答案:

答案 0 :(得分:3)

我想你可能会想要这样的东西:

class decorator:
    def __init__ (self, decorArg):
        self.arg = decorArg

    def __call__ (self, fn):
        print "I'm decoratin!"
        print self.arg
        return fn

class MyClass (object):
    def __init__ (self):
        self.list = []

    @decorator ("foo")
    def my_function (self, funcArg = None):
        print "Hi"
        print funcArg

MyClass ().my_function ("bar")

或者使用BlackNight指出的嵌套函数:

def decorator (decorArg):
    def f (fn):
        print "I'm decoratin!"
        print decorArg
        return fn
    return f