Creating a new instance of the object still contains old data

I have a file that does some analysis of the object that I pass to it

something like that:

test.py :

 class Test: var_array = [] def add_var(self, new_var): self.var_array.append(new_var) def run(test): for var in test.var_array: print var 

I have another file where I define the information I want to process

test2.py :

 import os import sys TEST_DIR = os.path.dirname(os.path.abspath(__file__)) if TEST_DIR not in sys.path: sys.path.append(TEST_DIR) from test import * test = Test() test.add_var('foo') run(test) 

so if i run this several times

 In [1]: %run test2.py foo In [2]: %run test2.py foo foo In [3]: %run test2.py foo foo foo 

What am I doing wrong? Should test = Test() create a new instance of the object?

+4
source share
1 answer

The following var_array code has a class variable (which is shared by the entire instance of Test objects):

 class Test: var_array = [] 

To define an instance variable, you must initialize it in the __init__ method as follows:

 class Test: def __init__(self): self.var_array = [] 
+8
source

All Articles