我知道这已经被记录在堆栈溢出的某个地方,但我一辈子都找不到它。。。我很乐意接受任何相关链接。你知道吗
我有以下代码:
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]
为什么在使用默认构造函数值时,数组会随着后续构造而增长?你知道吗
@agf找到了回答这个问题的链接:"Least Astonishment" and the Mutable Default Argument
该链接的公认响应指向以下有用的解释:http://effbot.org/zone/default-values.htm
相关问题 更多 >
编程相关推荐