Python class 实例未在方法结束时被销毁

Python class instance not being destroyed at end of method

我首先要说这是 IPython 中的 运行,如果它有所不同,请使用 Spyder IDE。我是 Python 的新手,但能说流利的其他语言。

我有一个 class 实例化并在函数中使用,如下所示。我从一个很长的阅读和处理算法中简化了代码。第一次我 运行 这个文件并调用 ReadFile() 时一切正常。任何后续 运行 崩溃,主要是因为 m_seclist 和 m_headers 已经包含数据。

我对 classes 的理解来自 C++,PHP 和 VB 所以我可能不符合我的假设,但由于 class 是在一个函数(即本地范围),实例不应该在函数结束时被完全销毁吗?在这种情况下,它看起来肯定不是,或者至少有一些变量幸存下来。我是不是误解了 Python 如何处理 class 个实例?

class Reader:
    m_headers = []
    m_seclist = []


    def __init__(self, filename):
        fh = open(filename, 'r')
        file_contents = fh.read().splitlines()
        fh.close()

        dataPointList = []

        for line in file_contents:
            for each section in the file (more code here)
                thisLine = line.split()
                dataPointList.append((float(thisLine[1]), float(thisLine[0])))
            m_seclist.append(dataPointList)
            dataPointList = []

    def getData(self, index):
        return m_seclist[index][0]

  #end of class
   def ReadFile(filename):
       my_instance = Reader(filename)
       output = my_instance.getData(2)
       return output

如果我能澄清一些事情,请大声喊叫。

您的问题是您存储数据的方式:

Class 属性存储在 class 中并在 class.

的所有实例之间共享

实例属性,而是按实例计数。

而不是

class Reader:
    m_headers = []
    m_seclist = []


    def __init__(self, filename):

class Reader:
    def __init__(self, filename):
        self.m_headers = []
        self.m_seclist = []
        ...

然后它们在每个实例中都是新的和新鲜的。

您误解了 class 和实例成员。你用这个做什么:

class Reader:
    m_headers = []
    m_seclist = []

声明 class 成员。他们活了下来。

你想要的是这个,哦,python 中的惯例是只用 _ 私有成员作为前缀。我还添加了 with 语句,这是处理需要关闭的资源的首选。

class Reader:

    def __init__(self, filename):
        self._headers = [] # This creates instance members
        self._seclist = []
        with open(filename, 'r') as fh: # With statement will auto close fh
            file_contents = fh.read().splitlines()

        for line in file_contents:
            dataPointList = []
            for each section in the file (more code here)
                thisLine = line.split()
                dataPointList.append((float(thisLine[1]), float(thisLine[0])))
            self._seclist.append(dataPointList)

    def getData(self, index):
        return self._seclist[index][0]

def ReadFile(filename):
    my_instance = Reader(filename)
    output = my_instance.getData(2)
    return output