Page 1 of 1

A confusing problem with Python instance variable

Posted: Sat Dec 11, 2010 1:59 pm
by Sanddman
E.g.

Create a python class say A

Class A:

def __init__(self, Variable=[]):
self.Variable=Variable

If I create a few instances without specifying Variable, say

X = A()
Y = A()

then X.Variable.append(something) will add that something to Y even though I defined Variable to be an instance variable. If I add

if Variable:
self.Variable=Variable
Else:
self.Variable = []

then the problem is solved.

I refuse to believe python is that dumb...Or am I just not following the right format?

Re: A confusing problem with Python instance variable

Posted: Sat Dec 11, 2010 11:12 pm
by fortaat
The problem with:

self.Variable=Variable

Is that every instance will be linked to the Variable dictionary. Every change you do to Variable would reflect on every instance. The following line:

self.Variable = []

Solved your problem because it initialized every instance with a different empty dictionary.
An easy solution would be to copy the dictionary upon initialization, and thus each instance would have its own copy of Variable:

Code: Select all

import copy

class A:

    def __init__(self, Variable=[]):
        self.Variable = copy.deepcopy(Variable)

Re: A confusing problem with Python instance variable

Posted: Sun Dec 12, 2010 9:21 pm
by Sanddman
thanks! That IS a better solution !