1

我对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

在我的检查功能中,我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 文件中(真的不知道这是否有很大的不同)我想得到这样的错误日志:

import my_functions

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

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

如果有人知道更好的方法来做到这一点,我很想听听你的建议。

4

1 回答 1

1

您的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()

我在这里所做的是将引用从您的out实例更改OutputLog为类本身,并将其更改为methodsclassmethods以便您可以自由调用它们。


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

于 2020-05-19T08:24:10.590 回答