Two instances share an attribute

Cameron Simpson cs at zip.com.au
Sat Nov 15 22:50:09 CET 2008


On 15Nov2008 22:41, Filip Gruszczyński <gruszczy at gmail.com> wrote:
| I really don't understand, what's happening with the following code.
| Am I doing something wrong?

Yes. This is a common mistake:

| class EnumeratedContent:
|         def __init__(self, values = []):
|                 self.values_ = values

The "values = []" happens at class definition time, not instance
definition time. So when "values" is not supplied, the same list
is reused as the default value.

The usual idiom is this:

  class EnumeratedContent:
          def __init__(self, values = None):
                  if values is None:
                      values = []
                  self.values_ = values

which makes a new [] during the instance creation.

Cheers,
-- 
Cameron Simpson <cs at zip.com.au> DoD#743
http://www.cskk.ezoshosting.com/cs/

If you don't live on the edge, you're taking up too much space. - t-shirt



More information about the Python-list mailing list