10

I have a file that runs some analysis on an object I pass to it

something like this:

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 processed

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 multiple 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? Shouldn't test = Test() create a new instance of the object?

Ben
  • 6,986
  • 6
  • 44
  • 71

1 Answers1

15

In the following code var_array is class variable (which is shared by all instance of Test objects):

class Test:
    var_array = []

To define instance variable, you should initialize it in the __init__ method as follow:

class Test:
    def __init__(self):
        self.var_array = []
falsetru
  • 357,413
  • 63
  • 732
  • 636