iga*_*rav 0 python factory decorator python-2.7 python-decorators
当decorator工厂接受参数并仍然装饰一个函数时,装饰器不带参数会让人感到困惑
在描述时使用它会很有帮助.
编辑:混淆是一个例子:
def before_run(func):
print "hello from before run"
def handle_arg(a,b):
if(a>0):
a= 100
return func(a,b)
return handle_arg
@before_run
def running_func(a,b):
print "a",a,"b", b
return a+b
Run Code Online (Sandbox Code Playgroud)
编辑:有没有办法通过添加日志选项(true或false)使用装饰工厂来做到这一点?
装饰器工厂只是一个可调用的,可以生成实际的装饰器.它用于"配置"装饰器.
所以代替:
@decorator
def decorated_function():
Run Code Online (Sandbox Code Playgroud)
你用的是:
@decorator_factory(arg1, arg2)
def decorated_function():
Run Code Online (Sandbox Code Playgroud)
并且该调用将返回使用的实际装饰器.
这通常通过将装饰器嵌套在另一个函数中来实现,并使用该新外部函数的参数来调整返回的装饰器的行为.
对于您的样本装饰器,缩进您的装饰器(您可能希望重命名它以减少混淆)并将其包装在带有logging参数的工厂函数中:
def before_run(logging=True):
def decorator(func):
print "hello from before run"
def handle_arg(a,b):
if(a>0):
if logging:
print "Altering argument a to 100"
a = 100
return func(a,b)
return handle_arg
return decorator
Run Code Online (Sandbox Code Playgroud)
我重命名了你的原始before_run()装饰器功能,decorator以明确这是工厂生产的装饰器.它最后返回; 此装饰器函数logging用作闭包来打开或关闭日志记录.