Python类初始化和内存模型行为

时间:2011-09-01 13:08:34

标签: python

我知道这已经在Stack Overflow上的某处记录过了,但我不能在我的生活中找到它...我会很乐意接受任何相关的链接。

我有以下代码:

class A:
    def __init__(self, x=[]):
        x += [1]
        print id(x), x

print "Try with default:"
a = A()
b = A()
c = A()
d = A()

print "Try with custom:"
a = A([1])
b = A([2])
c = A([3])
d = A([4])

生成以下输出:

Try with default:
4342272584 [1]
4342272584 [1, 1]
4342272584 [1, 1, 1]
4342272584 [1, 1, 1, 1]
Try with custom:
4342456688 [1, 1]
4342456688 [2, 1]
4342456688 [3, 1]
4342456688 [4, 1]

为什么在使用默认构造函数值时,数组会在每个后续构造中增长?

1 个答案:

答案 0 :(得分:0)

@agf提出了回答问题的链接:"Least Astonishment" and the Mutable Default Argument

该链接的已接受响应指向以下有用的解释:http://effbot.org/zone/default-values.htm