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?
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 = []
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With