[英]In python when we assign a new value to a variable what happens to the old one?
I know that there are other questions like this but they don't answer what happens to the previous value after reassignment, that's why I decided to post a new question.我知道还有其他类似的问题,但他们没有回答重新分配后以前的值会发生什么,这就是我决定发布一个新问题的原因。 So far I've learned that everything in python is an object, even the variables of type int, float, string, bool are objects, I've read somewhere that when we assign a variable
num = 11
then num is not actually storing the value of " 11 " in it but instead it is a pointer which is pointing at a certain location in memory where " 11 " is stored, and if we tried to reassign a value to num num = 22
then it will just stop pointing at " 11 " and start pointing at that new value " 22 " which will be stored in a different location in the memory, So my question is that what happens to the previous value ie 11
does that get free'd or deleted??到目前为止,我已经了解到 python 中的所有内容都是 object,即使是 int、float、string、bool 类型的变量也是对象,我在某处读到,当我们分配一个变量
num = 11
时,num 实际上并没有存储“ 11 ”的值,但它是一个指针,指向 memory 中存储“ 11 ”的某个位置,如果我们尝试将值重新分配给 num num = 22
那么它将停止指向“ 11 ”并开始指向新值“ 22 ”,它将存储在 memory 中的不同位置,所以我的问题是前一个值会发生什么,即11
会被释放或删除吗?
Python keeps track of how many references a particular variable has. Python 跟踪特定变量有多少引用。 If there isn't any reference to a particular value it would be cleaned which is also known as
Garbage Collection
.如果没有对特定值的任何引用,它将被清理,这也称为
Garbage Collection
。 So in your case 11
would be removed (garbage collected) by python as soon as it loses the reference.因此,在您的情况下,一旦失去参考,python 将删除(收集垃圾)
11
。
If there is no longer any reference to an object, it becomes eligible for garbage collection.如果不再有任何对 object 的引用,它就有资格进行垃圾收集。 Usually, it happens immediately.
通常,它会立即发生。
It's possible for a reference cycle to exist, one simple case being an object whose reference count is non-zero because it holds the only reference to itself.可能存在引用循环,一个简单的情况是 object,其引用计数不为零,因为它拥有对自身的唯一引用。
>>> a = [] # A list with a reference count of 1
>>> a.append(a) # List now has a reference count of 2: a and a[0]
>>> del a # List has a reference count of 1, but no name refers to the list
A separate algorithm is used by a Python implementation to periodically scan all exiting objects to look for such cycles and delete objects that cannot be accessed from the Python code anymore. Python 实现使用单独的算法定期扫描所有现有对象以查找此类循环并删除无法从 Python 代码中访问的对象。
I had a doubt regarding that answer,after the execution of del a would the list still exist in memory?我对这个答案有疑问,在执行 del a 之后,memory 中是否仍然存在该列表? And after the execution of.append(a) would a copy of a be created to which the element of list references or would the element of list reference to the original list
并且在执行 .append(a) 之后,将创建列表元素引用的 a 的副本,或者列表元素引用原始列表
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.