为什么一个实例变量,它是一个列表,会在for循环中增长?

Why does an instance variable, which is a list, grow in a for loop?

在下面的代码中,我希望在 for 循环中每次都会创建一个名为 'obj' 的 MyClass 的新实例。因此,每次输出都应该是[1]。但是 obj.mylist 似乎在增长。我错过了什么?

class MyClass:
    def __init__( self, mylist_=[] ):
        self.mylist = mylist_ 

    def addData( self ):
        self.mylist.append( 1 )

for i in range(5):
    obj = MyClass()
    obj.addData()
    print obj.mylist

输出为:

[1]
[1, 1]
[1, 1, 1]
[1, 1, 1, 1]
[1, 1, 1, 1, 1]

长话短说,在执行定义函数的语句时,创建一次参数的默认值。

请参考official documentation:

The default values are evaluated at the point of function definition in the defining scope, so that…

<…>

Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes.

<…>

4.7.1. Default Argument Values — Python 3.5.2 documentation.

此参考资料还包含不遵守警告的示例 — 一个非常相似的案例和观察到的行为。

其他参考资料: