Python 3.6:值的内存地址与变量的内存地址 [英] Python 3.6: Memory address of a value vs Memory address of a variable

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

问题描述

我当前正在使用python 3.6,并且正在使用id()函数. 当我在IDLE中运行以下代码时,

I am currently using python 3.6, and I was playing around with the id() function. When I run the following code in IDLE,

x = 1

print(id(x),id(1))

print(id(x), id(1))

两个内存地址相同. (对我来说是1499456272)我的理解是整数1,它是一个对象,具有一个内存地址,并且当将该对象分配给x时,该变量将获得该对象的相同内存地址. (不确定这是否正确)

The two memory addresses are the same. (1499456272 for me) My understanding is the integer 1, which is an object, has a memory address, and when the object is assigned to x, the variable gains the same memory address of the object. (not sure if this is correct)

例如,当我使用字符串复制上述代码时

When I replicate the above code using a string, for instance

s ="a"

print(id(s),id("a"))

print(id(s), id("a"))

我也得到两个相同的内存地址.再次,我目前为何会发生这种情况的原因与上述相同.

I also get two memory addresses which are the same. Again, my current reasoning for why this occurs is the same as above.

但是,当我使用列表尝试此操作时,我没有获得相同的内存地址.例如

However, when I try this using lists, I don't get the same memory address. For example,

l = [1]

print(id(l),id([1]))

print(id(l), id([1]))

给我1499456272和67146456.

gives me 1499456272 and 67146456.

有人可以向我解释为什么会这样吗?也许我目前关于整数和字符串为何具有相同的内存地址的推理是有缺陷的.谢谢:D

Can anyone explain to me why this occurs? Perhaps my current reasoning for why ints and strings have the same memory address is flawed. Thanks :D

推荐答案

cPython会实习从-5256的所有整数以及字符串文字.这意味着每当您获得这样的值时,Python就会知道它在内存中有一个副本,并返回相同的对象.

cPython interns all integers from -5 to 256 as well as string literals. This means whenever you get such a value, Python knows it has a copie of it in memory and returns the same object.

尽管,这两种类型的发生方式都不同.

Although, the way this happens is different for both types.

对于整数,这些值始终是内在的,从而使过程是动态的.

For integers, those values are always interned, allowing the process to be dynamic.

另一方面,字符串实习在编译时发生,因此特定于字符串文字.

On the other hand, string interning happens at compilation and thus is specific to string literals.

我们可以用is做一些实验,这等效于比较活动对象的id.

We can do some experiment with is which is equivalent to comparing id of live objects.

x = 1 + 1
y = 3 - 1
x is y # True

x = 'b'
y = 'b'
x is y # True

x = 257
y = 257
x is y # False

x = 'ab'.replace('a', '')
y = 'b'
x is y # False

尽管其他类型的对象(例如list)不是这种情况,即因为它们是可变的,所以您绝对不希望返回相同的对象.

Although, this is not the case for objects of other types, such as list, namely because they are mutable, so you absolutely would not want the same object to be returned.

[] is [] # False

尽管,最重要的是,这是一个优化实现,您不应在代码中依赖它.通常,假定不同的表达式返回不同的对象,以上是例外.

Although, the bottom line is that this is an optimisation implementation and you should not rely on it in your code. In general, assume that different expressions return different objects, for the above are exceptions.

这篇关于Python 3.6:值的内存地址与变量的内存地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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