了解python的内存模型 [英] Understanding python's memory model

查看:100
本文介绍了了解python的内存模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下日志:

>>> y = 20000
>>> id(y)
36638928
>>> y = 1000000
>>> id(y)
36639264

>>> y = 20000
>>> id(y)
36638928
>>> y = 1000000
>>> id(y)
36639264

如您所见,更改y的值后,其ID也随之更改.
这是否意味着int是不可变的?幕后发生了什么?

As you can see, after changing the value of y, it's id changed as well.
Does it mean that int is immutable? what is happening behind the scenes?

谢谢!

推荐答案

是的,整数是不可变的.您需要意识到的是:

Yes, integers are immutable. What you need to realize is that:

  1. 变量只是用于引用对象的名称.

  1. A variable is simply a name which you use to reference an object.

200001000000是两个唯一整数对象.这意味着它们永远不会同时共享相同的内存地址.

20000 and 1000000 are two unique integer objects. This means that they will never share the same memory address simultaneously.

简单来说,当您执行以下行时:

In simple terms, when you execute this line:

y = 20000

发生两件事:

  1. 在对象空间中创建了一个整数对象20000.

在名称空间中创建一个名称y,并指向该对象.

A name y is created in the namespace and pointed to that object.

执行此操作时:

y = 1000000

又发生了两件事:

  1. 在对象空间中创建了一个新的整数对象1000000.

名称y更改为指向该对象,而不是20000.

The name y is changed to point to that object instead of 20000.

这篇关于了解python的内存模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆