我有一个名为Timer的装饰师,现在理想的情况是使用这样的装饰器:
@Timer
def function(...):
return None但是,这会在调用function时一直调用Timer。当然,当您想要在特定实例下调用它时,您可以使用像普通函数这样的装饰器来完成此操作:
function = Timer(function)然而,这看起来不漂亮(我知道,我很挑剔)。那么,是否有一种方法可以对函数进行包装,比如测试文件中的所有用例?所以,就像:
from app import cheese
@Timer # Syntax error
cheese # Syntax error注意,如果您将它放在实际函数定义之上,它只对这个特定的文件使用装饰符,而不是一直使用它。
发布于 2013-10-03 13:01:02
如果您可以在文件顶部启用/禁用(即,您知道何时加载文件,无论是否启用它们),则可以使用启用/禁用解码器。
如果不是..。您没有发布装饰器的源代码,但是它没有理由不能引用包装代码本身中启用/禁用的全局变量。也就是说,一个装饰师看起来是这样的:
@simple_decorator
def my_simple_logging_decorator(func):
def you_will_never_see_this_name(*args, **kwargs):
print 'calling {}'.format(func.__name__)
return func(*args, **kwargs)
return you_will_never_see_this_name(来自https://wiki.python.org/moin/PythonDecoratorLibrary)
只需为添加的代码添加一个保护程序,即
@simple_decorator
def my_simple_logging_decorator(func):
def you_will_never_see_this_name(*args, **kwargs):
# Added/modified code starts here
if globalvar:
print 'calling {}'.format(func.__name__)
# End modified code
return func(*args, **kwargs)
return you_will_never_see_this_namehttps://stackoverflow.com/questions/19159081
复制相似问题