Re: Two instances share an attribute

2008-11-15 Thread Filip Gruszczyński
Every day something new. Thanks a lot :)

2008/11/15 Cameron Simpson <[EMAIL PROTECTED]>:
> On 15Nov2008 22:41, Filip Gruszczyński <[EMAIL PROTECTED]> 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 <[EMAIL PROTECTED]> 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
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Filip Gruszczyński
--
http://mail.python.org/mailman/listinfo/python-list


Re: Two instances share an attribute

2008-11-15 Thread Cameron Simpson
On 15Nov2008 22:41, Filip Gruszczyński <[EMAIL PROTECTED]> 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 <[EMAIL PROTECTED]> 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
--
http://mail.python.org/mailman/listinfo/python-list