0

python装饰器函数是否支持参数a如何实现

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 。它也不起作用。到目前为止,我想知道这是否可能

4

1 回答 1

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
于 2013-03-02T07:04:25.153 回答