相关疑难解决方法(0)

如何将额外的参数传递给Python装饰器?

我有一个像下面的装饰.

def myDecorator(test_func):
    return callSomeWrapper(test_func)
def callSomeWrapper(test_func):
    return test_func
@myDecorator
def someFunc():
    print 'hello'
Run Code Online (Sandbox Code Playgroud)

我想增强这个装饰器来接受另一个如下所示的参数

def myDecorator(test_func,logIt):
    if logIt:
        print "Calling Function: " + test_func.__name__
    return callSomeWrapper(test_func)
@myDecorator(False)
def someFunc():
    print 'Hello'
Run Code Online (Sandbox Code Playgroud)

但是这段代码给出了错误,

TypeError:myDecorator()只需要2个参数(给定1个)

为什么函数不会自动通过?如何将函数显式传递给装饰器函数?

python python-2.7 python-decorators

79
推荐指数
4
解决办法
5万
查看次数

标签 统计

python ×1

python-2.7 ×1

python-decorators ×1