Python Class Initialization and Memory Model Behavior [duplicate]
I know this has been documented somewhere on Stack Overflow, but I can't for the life of me find it... I'll be happy to accept any relevant links.
I have the following code:
class A:
def __init__(self, x=[]):
x += [1]
print id(x), x
print "Try with default:"
a = A()
b = A()
c = A()
d = A()
p开发者_如何学JAVArint "Try with custom:"
a = A([1])
b = A([2])
c = A([3])
d = A([4])
Which generates the following output:
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]
Why is it when using the default constructor value, the array grows on each subsequent construction?
@agf came up with the link that answers the question: "Least Astonishment" and the Mutable Default Argument
The accepted response for that link points to the following useful explanation: http://effbot.org/zone/default-values.htm
精彩评论