Python base classes share attributes?
Posted
by tad
on Stack Overflow
See other posts from Stack Overflow
or by tad
Published on 2010-05-21T04:06:03Z
Indexed on
2010/05/21
4:10 UTC
Read the original article
Hit count: 229
python
Code in test.py:
class Base(object):
def __init__(self, l=[]):
self.l = l
def add(self, num):
self.l.append(num)
def remove(self, num):
self.l.remove(num)
class Derived(Base):
def __init__(self, l=[]):
super(Derived, self).__init__(l)
Python shell session:
Python 2.6.5 (r265:79063, Apr 1 2010, 05:22:20)
[GCC 4.4.3 20100316 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
>>> a = test.Derived()
>>> b = test.Derived()
>>> a.l
[]
>>> b.l
[]
>>> a.add(1)
>>> a.l
[1]
>>> b.l
[1]
>>> c = test.Derived()
>>> c.l
[1]
I was expecting "C++-like" behavior, in which each derived object contains its own instance of the base class. Is this still the case? Why does each object appear to share the same list instance?
© Stack Overflow or respective owner