gpt4 book ai didi

python - 打印 Python 变量的内存地址

转载 作者:IT老高 更新时间:2023-10-28 21:43:16 35 4
gpt4 key购买 nike

如何在 Python 2.7 中打印变量的内存地址?我知道 id() 返回变量或对象的“id”,但这不会返回我期望看到的内存地址的预期 0x3357e182 样式。我想做一些类似 print &x 的事情,例如,其中 x 是 C++ int 变量。如何在 Python 中做到这一点?

最佳答案

id 是您要使用的方法:将其转换为十六进制:

hex(id(variable_here))

例如:

x = 4
print hex(id(x))

给我:

0x9cf10c

你想要什么,对吧?

(有趣的是,将两个变量绑定(bind)到同一个 int 可能会导致使用相同的内存地址。)
试试:

x = 4
y = 4
w = 9999
v = 9999
a = 12345678
b = 12345678
print hex(id(x))
print hex(id(y))
print hex(id(w))
print hex(id(v))
print hex(id(a))
print hex(id(b))

这给了我相同的对,即使是大整数。

关于python - 打印 Python 变量的内存地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16408472/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com