可能重复:
“Least Astonishment” in Python: The Mutable Default Argument了解Python的继承和初始化
在Python 2.7,考虑我有以下代码:
class Base(object):
# Variant 1
def __init__(self, records=[]):
self._records = records
# Variant 2
# def __init__(self, records=[]):
# self._records = []
# if records:
# self._records = records
def append(self, value):
self._records.append(value)
class ChildA(Base):
pass
class ChildB(Base):
pass
a = ChildA()
b = ChildB()
a.append(100)
b.append(200)
print a._records
print b._records
如果我使用的变体1初始化我的基类self._records的行为就像一个类变量。执行使用变体1初始化我的基类中的代码,我得到的输出中:
[100, 200]
[100, 200]
使用变种2初始化我的基类,self._records就像一个实例变量(如预期)。执行使用变种2初始化我的基类中的代码,我得到的输出:
[100]
[200]
的是这两种变体之间的区别?为什么变体1的工作方式与变体2不同?非常感谢你的帮助!