Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating new object instance still has old data in it [duplicate]

Tags:

python

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?

like image 864
Ben Avatar asked Sep 20 '13 16:09

Ben


1 Answers

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 = []
like image 164
falsetru Avatar answered Oct 26 '22 13:10

falsetru