Unexpected behavior when initializing class
Arnaud Delobelle
arnodel at googlemail.com
Wed Nov 28 12:13:25 EST 2007
On Nov 28, 3:04 pm, Mel <mwil... at the-wire.com> wrote:
> Paul Rudin wrote:
> > "alfred.fa... at gmail.com" <alfred.fa... at gmail.com> writes:
> > A common paradigm to get round this - assuming you want a different
> > empty list each time - is something like:
>
> > def __init__(self, v = None):
> > self.values = v if v else []
>
> > (or maybe test explicitly for None, but you get the idea.)
>
> Do test explicitly for None. Otherwise, if you do
>
> a = []
> x = ThatClass (a)
>
> it will so happen that x.values will be an empty list, but it won't be
> the same list as a.
>
> Mel.
Yes. Another much safer possibility is to make a copy of the initial
v:
def __init__(self, values=[]):
self.values = list(values)
As a nice side effect, the object can be initialised with any
iterable.
--
Arnaud
More information about the Python-list
mailing list