Python将类保留在内存中

2024-05-18 05:51:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python相当陌生,所以如果我的问题没有意义,请纠正我

我正在写一个小脚本,它应该检查一些数据并记录失败的数据。为了更好地了解情况,我维护了两个文件。一个是我的主要功能,另一个是其他功能

要记录失败的数据,我有以下类:

 class OutputLog():
  def __init__(self):
    self.errorLog = []

  def log(self, item: str):    #write data to errorLog if called
    self.errorLog.append(item)
    self.errorLog.append('\n')

  def write(self):             #return errorLog
    return self.errorLog

在我的check函数中,我调用OutputLog.log(),如下所示:

####### Check Data ########
class Check:
  def __init__(self, sortedData):
    self.sortedData = sortedData

## Check if name got spaces and log them
  def nameSpace(self):
    out = OutputLog()
    for column in self.sortedData:
      item = column[0]
      if ' ' in item:
        out.log(item)      #Call Output log
      else:
        continue

在另一个.py文件中的main函数中(我不知道这是否会产生巨大的差异),我希望得到如下错误日志:

import my_functions

def main():
  out = my_functions.OutputLog()
  c = my_functions.Check()
  c.nameSpace()
  print(out.write())

但像这样,我的错误日志仍然是空的。 有没有一种方法可以让我只拥有OutputLog类的一个实例,或者我需要公开errorLog变量

如果有人知道更好的方法,我很想听听你的建议


Tags: 数据selflogifmydefcheck记录
1条回答
网友
1楼 · 发布于 2024-05-18 05:51:52

您的out变量位于不同的名称空间中,因此不相互引用。但是,您可以做的是将errorLog变量更改为类属性,而不是实例属性

class OutputLog:
    errorLog = []

    # Creates a classmethod that can be called without a create instance.
    @classmethod
    def log(self, item: str): 
        OutputLog.errorLog.append(item)

    # Creates a classmethod that can be called without a create instance.
    @classmethod
    def write(self):
        return OutputLog.errorLog

class Check:
    def __init__(self, sortedData):
        self.sortedData = sortedData

    def nameSpace(self):
        for column in self.sortedData:
            item = column[0]
            if ' ' in item:
                OutputLog.log(item)  # Calling the class-method directly, not an instance
            else:
                continue

您没有提供任何数据来测试Check类,因此我创建了自己的数据:

import my_functions

def main():
    c = my_functions.Check([" " for i in range(10)])
    c.nameSpace()
    print(my_functions.OutputLog.write()) # Output: [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']

main()

我在这里所做的是将OutputLogout实例的引用更改为类本身,并将methods更改为classmethods,以便可以自由调用它们


作为旁注,您应该遵循PEP 8,并在代码中使用4行缩进,以创建更好的可读性和标准化代码,以便将来更容易与其他人协作

相关问题 更多 >