Python中的对象创建修改后的变量发生了什么?

2024-06-17 12:19:58 发布

您现在位置:Python中文网/ 问答频道 /正文

在接触了Python更深入的工作方式之后,我开始理解,分配一个变量等于创建一个新对象,这个对象有自己的特定地址,而不管分配给这个对象的变量名是什么。你知道吗

不过,在这种情况下,我不禁要问,后来创建和修改的对象会发生什么。它坐在那里消耗记忆吗?你知道吗

脑海中的情景是这样的:

# Creates object with id 10101001 (random numbers)
x = 5

# Creates object with id 10010010 using the value from object 10101001.
x += 10

id为10101001的对象会发生什么情况? 出于好奇,为什么对象需要一个ID和一个reference变量名,用变量名分配地址不是更好吗?你知道吗

我事先为这个问题可能引起某人的嘲笑而道歉。你知道吗


Tags: the对象记忆idobject地址with方式
2条回答

这是Ned Batchelder今年在PyCon上关于Python如何管理变量的精彩演讲。你知道吗

https://www.youtube.com/watch?v=_AEJHKGk9ns

我认为这将有助于消除你的一些困惑。你知道吗

首先Augmented assignment statements状态:

An augmented assignment expression like x += 1 can be rewritten x = x + 1 to achieve a similar, but not exactly equal effect. In the augmented version, x is only evaluated once. Also, when possible, the actual operation is performed in-place, meaning that rather than creating a new object and assigning that to the target, the old object is modified instead.

因此,根据x的类型,这可能不会创建新对象。你知道吗

Python是引用计数的。因此id为10101001的对象的引用计数减少。如果此计数为零,则几乎立即释放。但大多数低范围整数都是缓存的。有关所有详细信息,请参阅Objects, Types and Reference Counts。你知道吗

关于对象的id

CPython implementation detail: This is the address of the object in memory.

所以基本上id和reference是一样的。变量名只是对象本身的绑定。你知道吗

相关问题 更多 >