코드 :Python 기본 클래스는 속성을 공유합니까? 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 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]
내가 기대 한 - 각 파생 된 개체는 기본 클래스의 고유 한 인스턴스를 포함하는 행동, "C++를 같이". 아직도 그렇습니까? 각 개체가 같은 목록 인스턴스를 공유하는 것처럼 보이는 이유는 무엇입니까?
가능한 중복 (http://stackoverflow.com/questions/1132941/least-astonishment-in-python- the-mutable-default-argument) –