Unexpected behavior when initializing class
Gary Herron
gherron at islandtraining.com
Wed Nov 28 03:38:15 EST 2007
alfred.fazio at gmail.com wrote:
> 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.
>
This is a *feature* of Python that bytes *ever* newbie at least once. ;-)
See
http://www.python.org/doc/faq/general/#why-are-default-values-shared-between-objects
> class Test(object):
> def __init__(self, v=[]):
> self.values = v
>
> def addValue(self, v):
> self.values += [v]
> return
>
> a = Test()
> a.addValue(1)
> print a.values # Should print [1]
> b = Test()
> print b.values # Should print empty list
> b.addValue(2)
> print a.values # Should print [1]
>
> The output I get is:
>
> [1]
> [1]
> [1, 2]
>
> The output I am expecting is:
>
> [1]
> []
> [1]
>
> Another strange thing is that if I initialize with a different value,
> the new instance will not share the 'values' attribute with the other
> two:
>
> c = Test([9])
> print c.values # Prints [9] as it should
> print a.values # Still prints [1, 2]
>
> There is something I clearly don't understand here. Can anybody
> explain? Thanks!
>
> Python 2.4.4 (#1, Oct 23 2006, 13:58:18)
> [GCC 4.1.1 20061011 (Red Hat 4.1.1-30)] on linux2
>
> Alfred J. Fazio,
> afazio at smoothstone.com
>
More information about the Python-list
mailing list