Unexpected behavior when initializing class

Paul Rudin paul.nospam at rudin.co.uk
Wed Nov 28 03:31:03 EST 2007


"alfred.fazio at gmail.com" <alfred.fazio at gmail.com> writes:

> Hello everybody,
>
>     I've banged my ahead around for a while trying to figure out why
> multiple instances of a class share the same instance variable.  I've
> stripped down my code to the following, which reproduces my problem.
>
> class Test(object):
>     def __init__(self, v=[]):
>         self.values = v

You have to understand that the default value for v - an empty list -
is made at compile time - and it's the *same* list every time it's
used i.e. if you don't pass in a value for v when you make new
instances of your class.

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.)



More information about the Python-list mailing list