What am i doing Wrong?

Aldo Cortesi aldo at nullcube.com
Wed Sep 21 08:32:52 CEST 2005

Thus spake keithlackey (keithlackey at deegroup.com):

>       class structure:
>             def __init__(self, folders = []):

Here's your problem. To understand what's going on, you need to know two

        - Default arguments are only evaluated ONCE when the
          Python interpreter executes the class definition.
        - A list is a mutable object.

So, what's happening is that both your class instances are
getting the _same_ list as a default instantiation argument.
You are modifying the list through the first class instance,
and then seeing the same change when you view the list via the
second class instance.

As a rule of thumb, simply never use a mutable object as a
default argument to a function or method unless you really
know what you're doing, and actually want the behaviour
you're going to get. In your case, you probably want
something like:

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



Aldo Cortesi
aldo at nullcube.com
Off: (02) 9283 1131
Mob: 0419 492 863

More information about the Python-list mailing list