首页 > 解决方案 > 我应该如何正确记录我的类容器?

问题描述

我有以下情况:

class A():
    def __init__(self, log = True):
        self.log = log

    def __call__(self):
        if self.log:
             self.log ='\n'    # whatever no-Null string to reinitialize the log attribute at each call
        do_things()
             self.log += 'I did things'

class B()
    def __init__(self):
        self.a = A(log = True) 
        self.log_master = []

    def __call__(self):
        for i in range(num):
            self.a()
            self.log_master.append(a.log)
            self.log_master.append('other things')
        save_to_file(self.log_master)

所以我有一个用 classB实例初始化的类AB来电A。当调用该类时,A它会初始化一个字符串,该字符串用作记录操作的容器。通话结束时,B检查A' 的日志字符串并将其附加到log_master,除其他事项外。最后,所有内容log_master都保存到文件中。基本上我有两个类,其中一个用作另一个实例的容器。两者都在编写日志文件时“合作”。

我能感受到这种方法的恐怖。我的A代码中充满了丑陋的“if self.log: ..”。生成体面且可定制的日志文件的正确方法是什么?

标签: pythonlogging

解决方案


推荐阅读