dictionary containing instances of classes behaving oddly

Erik Johnson ejatsomewhere.com
Thu Dec 28 13:42:15 EST 2006


"Ben" <Benjamin.Barker at gmail.com> wrote in message
news:1167326178.386764.300200 at n51g2000cwc.googlegroups.com...

<snip>

> This seems to work without any errors. But bizzarely I find that
> whatever my record number, the instance of "my_class" is appended to
> every list. So in this case
>
> self.mop_list[0].my_list.append(my_class(Some data for the
> constructor))
>
> I would expect to append an instance of my_class to
> self.mop_list[0].my_list
>
> But annoyingly
>
> self.mop_list[0].my_list
> self.mop_list[3].my_list
> self.mop_list[7].my_list
>
> all have an instance of my_class created and appended to them. This is
> really confusing and quite annoying - I don't know whether anyone out
> there can make head or tail of what I'm doing wrong?

Well, it's a little bit difficult, but I think I actually know what's going
on. You probably need some code that looks something like this, to ensure
each object has it's own, independent list:

class record:
    def __init__(self, init_list=None):
        self.my_list = []
        if init_list is not None:
            self.my_list.extend(init_list)


Here's what I think you are doing, and below should make it clear why that
doesn't work:

class record:
    def __init__(self, init_list=[]):

That list above, the default initializer is constructed just once (when the
def statement executes)!

>>> class record:
...   def __init__(self, init_list=[]):
...     self.my_list = init_list
...
>>> r1 = record()
>>> r1.my_list
[]
>>> r2 = record()
>>> r2.my_list
[]
>>> r2.my_list.append('boo!')
>>> r1.my_list
['boo!']
>>>
>>> l1 = range(1, 4)
>>> l1
[1, 2, 3]
>>> r1 = record(l1)
>>> r2 = record(l1)
>>> r1.my_list
[1, 2, 3]
>>> r2.my_list
[1, 2, 3]
>>> r1.my_list.append(42)
>>> l1
[1, 2, 3, 42]
>>> r1.my_list
[1, 2, 3, 42]
>>> r2.my_list
[1, 2, 3, 42]
>>>





More information about the Python-list mailing list