[英]Can someone explain this python behavior to me?
Can someone explain this behavior? 有人可以解释这种行为吗? When I run the code, it prints 10, then 20. Why is
list_of_classes
being changed even though I only changed the value of bob? 当我运行代码时,它将显示10,然后是20。即使我仅更改了bob的值,为什么
list_of_classes
被更改了? Shouldn't I have to update the list with the new values? 我是否不必用新值更新列表?
class wooo():
def __init__(self,x,y,name):
self.x=x
self.y=y
self.name=name
bob=wooo(10,10,"bob")
joe=wooo(10,10,"joe")
list_of_classes=[bob,joe]
print(list_of_classes[0].x)
bob.x=20
print(list_of_classes[0].x)
10
20
10
10
Your lists contain references to the objects, not copies. 您的列表包含对对象的引用 ,而不是副本。
list_of_classes[0]
is a reference to the same object that bob
references. list_of_classes[0]
是对bob
引用的同一对象的引用。 You can create more references to the same object and the attribute change would be visible through all those references: 您可以为同一对象创建更多引用,并且所有这些引用都将显示属性更改:
>>> class wooo():
... def __init__(self,x,y,name):
... self.x=x
... self.y=y
... self.name=name
...
>>> bob=wooo(10,10,"bob")
>>> guido = bob
>>> guido.x
10
>>> guido.x = 20
>>> bob.x
20
>>> guido is bob
True
If you wanted to add copies of a class to the list, use the copy
module to create a deep copy of your instance: 如果要将类的副本添加到列表中,请使用
copy
模块创建实例的深层副本:
>>> import copy
>>> robert = copy.deepcopy(bob)
>>> robert.x
20
>>> bob.x = 30
>>> robert.x
20
>>> robert is bob
False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.