Help - strange behaviour from python list

Duncan Booth duncan.booth at invalid.invalid
Tue Apr 11 08:19:08 EDT 2006


Sean Hammond wrote:

> class Area:
>       def __init__(self, occupants = []):
>            self.occupants = occupants
> 
...
> I must be making some really stupid mistake, but this just doesn't
> look like the list behaviour I would expect. What's going on here?

Whenever you use the default value for occupants in the constructor you 
reuse the same list. Don't use mutable objects as default values:

def __init__(self, occupants=None):
    if occupants is None:
       self.occupants = []
    else:
       self.occupants = occupants



More information about the Python-list mailing list