Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do two class instances appear to be sharing the same data? [duplicate]

Tags:

python

class

I was doing some work in Python when I ran into an unexpected problem. I have a class, and two variables x and y. x and y are meant to be separate copies of the class each with their own data. So I set x equal to the class and give it some values, then do the same with y. Once I try to use that data though, I realize that I overwrote my values for x. It seems that I have not created two separate copies of the class to work with but instead two references to the same class. So here is the general example in code:

x = someClass()
x.set(2, 0)
y = someClass()
y.set(3, 0)
print(x)

The end result is that 3 is printed instead of 2. I want to create a separate "version" of the class to hold different data for each variable. Not sure as to how though. Using Python 3.3. Here is the code for the class:

class someClass:
    def __init__(self, list = [0,0,0,0,0,0,0,0,0,0]):
        self.list = list
    def __repr__(self):
        return str(self.list)
    def set(self, loc, val):
        if ((loc >= 0) & (loc <= 9)):
            self.list[loc] = val
like image 282
Spino Prime Avatar asked Aug 31 '25 01:08

Spino Prime


1 Answers

You fell into a common newbie trap for Python. Using a list as a default variable as you did with def __init__(self, list = [0,0,0,0,0,0,0,0,0,0]) means that all instances of that class share the same list instance as the value for that argument. See also "Least Astonishment" and the Mutable Default Argument

By the way, a common idiom if you want to use a container object such as a list as a default argument, is to instead use None and check for that. For example:

def __init__(self, values=None):
    if values is None:
        values = [0] * 10

Or whatever. Not quite as clearly self-documenting as default arguments but it works.

As a side note, don't use list as a variable name, as it shadows the (somewhat commonly used) list builtin.

like image 186
Iguananaut Avatar answered Sep 02 '25 14:09

Iguananaut