instance variable weirdness

Felipe Almeida Lessa felipe.lessa at gmail.com
Fri Apr 14 12:30:49 EDT 2006


Em Sex, 2006-04-14 às 09:18 -0700, wietse escreveu:
>     def __init__(self, name, collection=[]):

Never, ever, use the default as a list.

>         self.collection = collection

This will just make a reference of self.collection to the collection
argument.

>         inst.collection.append(i)

As list operations are done in place, you don't override the
self.collection variable, and all instances end up by having the same
list object.

To solve your problem, change 
    def __init__(self, name, collection=[]):
        BaseClass.__init__(self)
        self.name = name
        self.collection = collection # Will reuse the list
to
    def __init__(self, name, collection=None):
        BaseClass.__init__(self)
        self.name = name
        if collection is None:
            collection = [] # Will create a new list on every instance
        self.collection = collection


-- 
Felipe.




More information about the Python-list mailing list