Two instances share an attribute
Filip Gruszczyński
gruszczy at gmail.com
Sat Nov 15 16:52:27 EST 2008
Every day something new. Thanks a lot :)
2008/11/15 Cameron Simpson <cs at zip.com.au>:
> 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
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
Filip Gruszczyński
More information about the Python-list
mailing list