Python类实例在方法结束时不被破坏

问题描述:

我应该首先说这是在IPython中运行,如果它有所作为,则使用Spyder IDE。我在Python方面有点新手,但在其他语言中流利。Python类实例在方法结束时不被破坏

我有一个类被实例化并在一个函数中使用,如下所示。我已经通过非常长的读取和处理算法简化了代码。这一切工作正常,我第一次运行这个文件并调用ReadFile()。任何后继都会崩溃,主要是因为m_seclist和m_headers已经包含数据。我对类的理解来自C++,PHP和VB,所以我可能会忽略掉我的假设,但是当类在一个函数(即局部作用域)内实例化时,如果实例没有在功能?在这种情况下,它显然不是,或者至少有一些变量是存在的。我误解了Python如何处理类实例?

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 

如果我能澄清某事,大叫。

+0

您能否澄清您是如何注意到“某些变量正在存活”? – glglgl 2015-02-11 21:35:06

+0

和你的代码的其余部分在哪里?我没有看到任何对象的启动。 – 2015-02-11 21:36:37

+0

本质上,ReadFile函数在第二次运行时崩溃(即第一次运行后),并且在调试时打印m_seclist列表以发现它们包含数据的两个副本(例如1,2,3,1, 2,3它应该是1,2,3) – 2015-02-11 21:36:47

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

类属性存储在类和类的所有实例之间共享。

实例属性改为按每个实例计数。

而不是

class Reader: 
    m_headers = [] 
    m_seclist = [] 


    def __init__(self, filename): 

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

那么他们在每一个实例耳目一新。

+0

你如何使某个实例属性与共享相比? – 2015-02-11 21:39:37

+0

@TomKilney [阅读文档](https://docs.python.org/2/tutorial/classes.html)? – jonrsharpe 2015-02-11 21:40:15

+0

谢谢,我会的。我不能说我遇到过一个类变量会有用的情况,但是可能存在这种情况! – 2015-02-11 21:48:42

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

class Reader: 
    m_headers = [] 
    m_seclist = [] 

是声明类成员。他们幸存下来。

你想要的是这个,哦,在python约定是只是前缀_私人成员。我还添加了处理需要关闭的资源的首选语句。

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 
+0

为什么'_'?我不认为这是必要的... – glglgl 2015-02-11 21:43:15

+0

我刚刚将他的约定私有成员变量'm_varname'到Python的'self._varname' – Th30n 2015-02-11 21:46:10