unintentionaly shared attributes in two different instances

maxm maxm at mxm.dk
Thu Dec 13 09:01:50 EST 2001


I have this funny problem. When I make two objects from the class "Row" one
of the attributes is shared another one is not.

When I create the class like::

class Row:

    def __init__(self, title='', content=[]):
        self.title   = title
        self.content = content

    def append(self,item):
        self.content.append(item)

row1 = Row('Max M')
row1.append('aa')
row1.append('bb')

row2 = Row('sdf sdf')
row2.append('cc')
row2.append('dd')

print row1.content
print row2.content

I get the output:

>>>['aa', 'bb', 'cc', 'dd']
>>>['aa', 'bb', 'cc', 'dd']

It seems that when I don't pass a list to the __init__ method, that the init
finds the attribute of the row1 object, and appends to that.

When I change the __init__ method, I can make it work correctly:

# Not working

class Row:

    def __init__(self, title='', content=[]):
        self.title   = title
        self.content = content

# Working

class Row:

    def __init__(self, title='', content=None):
        self.title   = title
        self.content = content or []

I can also make it work by passing an empty list to init like::

row1 = Row('Max M',[])
row1.append('aa')
row1.append('bb')

row2 = Row('sdf sdf',[])
row2.append('cc')
row2.append('dd')

print row1.content
print row2.content

I get the output:

>>>['aa', 'bb']
>>>['cc', 'dd']

just as I would expect.

I run the code from inside PythonWin and it can sometimes hold instances in
memory, but this is rather weird I think.

Any ideas?

regards Max M





More information about the Python-list mailing list