我有一个模块,它是 C 程序的包装类。
每种方法都有不同的输入,但输出通常是相同的,即文件名。
class Wrapper(object):
def wrapper1(self, infile, outfile):
do_stuff
log.info('wrapper1:%s' %outfile)
在我意识到我想要这种行为之前,我已经编写了 50 个方法。
另外,必须有一种优雅的方式来添加记录器,而不需要将该行添加到所有方法中。
干杯
最佳答案
使用 decorator :
import functools
def log(func):
@functools.wraps(func)
def wrapper(self, infile, outfile):
retval = func(self, infile, outfile)
log.info('wrapper1:%s' %outfile)
return retval
return wrapper
class Wrapper(object):
@log
def wrapper1(self, infile, outfile):
do_stuff
关于Python:自动记录类中每个方法的名称和输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23281185/