[英]python mutable and immutable function arguments
I stumbled over a "strange behaviour"(as in strange for me) of python.我偶然发现了 python 的“奇怪行为”(对我来说很奇怪)。 I thought i created a list "a" trough passing the first element of ParamList, which is a list.
我以为我通过传递 ParamList 的第一个元素创建了一个列表“a”,这是一个列表。 Then i changed "a" in another function, but than also ParamList[0] also got changed.
然后我在另一个函数中更改了“a”,但 ParamList[0] 也被更改了。 I didn't expect that.
我没想到。
Look at the following minimal code看下面的最小代码
def f(ParamList):
b = ParamList[1]
a = ParamList[0]
print('id(ParamList[0]), id(a)', id(ParamList[0]), id(a))
a, b = Problemmaker(a,b)
print('a, b, ParamList', a, b, ParamList)
def Problemmaker(a,b):
a[2]=99
print('id(a)', id(a))
b = 55
return a,b
if __name__ == "__main__":
Initial = [[2,3,4],2]
f(Initial)
i already found out what, the problem is.我已经发现了什么,问题是。
So apparently what i did is, that "a" and ParamList[0] get referenced to the same adress.显然我所做的是,“a”和 ParamList[0] 被引用到同一个地址。
So i was thinking ok, "a" gets the value of ParamList[0] but in fact, all i did was referencing "a" to the same adress.所以我在想,“a”获得 ParamList[0] 的值,但实际上,我所做的只是将“a”引用到同一个地址。 So when i changed "a", the value that was stored in that adress also got changed and so got ParamList[0].
因此,当我更改“a”时,存储在该地址中的值也发生了更改,因此获得了 ParamList[0]。
So if i wan't to change "a" but not ParamList[0], i can create a new List for "a" and the problem is avoided.因此,如果我不想更改“a”但不更改 ParamList[0],我可以为“a”创建一个新列表,从而避免问题。
def f(ParamList):
b = ParamList[1]
a = [*ParamList[0]]
print('id(ParamList[0]), id(a)', id(ParamList[0]), id(a))
a, b = Problemmaker(a,b)
print('a, b, ParamList', a, b, ParamList)
def Problemmaker(a,b):
a[2]=99
print('id(ParamList[0]), id(a)', id(a))
b = 55
return a,b
if __name__ == "__main__":
Initial = [[2,3,4],2]
f(Initial)
This is emberassing, because i code in python for a long time know and i was always thinking that i know what's what, but yeah admitting this mistake hopefully makes me more meticulous.这很尴尬,因为我用 python 编写代码很长时间都知道,而且我一直认为我知道什么是什么,但是承认这个错误希望能让我更加细致。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.