Conditionals decoration of functions in Python
出于调试目的,我想编写一个函数来执行此操作:
我想用功能装饰器(我以前从来没有用过)。
实际上,我想用我在一些要点中介绍的一些
我不想创建这样的类。这是我的方法,但不起作用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import logging FORMAT = '%(asctime)s %(levelname)s %(message)s %(funcName)s' logging.basicConfig(filename='example.log', level=logging.DEBUG, format=FORMAT, datefmt='%m/%d/%Y %I:%M:%S %p') def debug(func): def _debug(deb=0, *args, **kwargs): if deb == 1: print(msg) func(*args, **kwargs) if deb == 2: logging.debug(msg) return _debug @debug def echo(msg, deb=0): pass if __name__ =="__main__": debug_mode = 1 echo("This is a debugging message!", debug_mode) |
如果我不通过参数调试模式就更好了,在decorator函数中,我可以直接从
代码的问题在于传递参数的方式。当你这样做时,你实际上是在调用
我不知道为什么你的代码中需要
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | import logging FORMAT = '%(asctime)s %(levelname)s %(message)s %(funcName)s' logging.basicConfig(filename='example.log', level=logging.DEBUG, format=FORMAT, datefmt='%m/%d/%Y %I:%M:%S %p') def debug(func): def _debug(msg, deb=0): if deb == 1: func(msg, deb) if deb == 2: print 'Log: ' + msg + ' Level: ' + str(deb) logging.debug(msg) return _debug @debug def echo(msg, deb): print 'Echo: ' + msg + ' Level: ' + str(deb) if __name__ =="__main__": echo("This is a debugging message!") echo("This is a debugging message!", 0) echo("This is a debugging message!", 1) echo("This is a debugging message!", 2) |
输出:
1 2 | Echo: This is a debugging message! Level: 1 Log: This is a debugging message! Level: 2 |
号