python是否在分配时复制对象? [英] Does python copy objects on assignment?
问题描述
我读到python中的assign不会复制它,就像在c中将对象的指针分配给c一样.
I read that the assign in python does not copy it works like it does in c where it assigns a pointer to an object.
但是当我调试此功能时:
But when I debug this function:
def popall(self):
objs = self.curstack
self.curstack = []
return objs
似乎正在进行某种复制.该函数运行后,obis充满了东西, self.curstack
为空...
It looks like some kind of copy is taking place. After this function runs obis is full of things and self.curstack
is empty…
因此正在进行一些复制.是深还是浅?
So some copy is going on. Is it deep or shallow?
推荐答案
它不会复制任何内容.只是分配给self.curstack
不会修改self.curstack
曾经引用的内容.它只是使self.curstack
引用其他内容.
It doesn't copy anything. It's just that assigning to self.curstack
does not modify whatever self.curstack
used to refer to. It just makes self.curstack
refer to something else.
这样想. self.curstack
指向一些东西.使用objs = self.curstack
,您可以使objs
指向相同的内容.使用self.curstack = []
,使self.curstack
指向一个空列表.这不会删除self.curstack
过去指向的任何内容;这些东西仍然存在,并且objs
仍然指向它.
Think of it this way. self.curstack
points to some stuff. With objs = self.curstack
you make objs
point to that same stuff. With self.curstack = []
, you make self.curstack
point to an empty list. This doesn't remove any of the stuff that self.curstack
used to point at; that stuff is still there and objs
is still pointing at it.
本文使用类似于标签标签的方式对其进行了解释
This article explains it using a nice analogy of label tags.
这篇关于python是否在分配时复制对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!