问题描述
如何在Python 2.7中打印变量的内存地址?我知道id()返回变量或对象的'id',但这不会返回我期望为内存地址看到的预期0x3357e182样式.我想做类似print &x
的操作,其中x例如是C ++ int变量.如何在Python中执行此操作?
How do I print the memory address of a variable in Python 2.7?I know id() returns the 'id' of a variable or object, but this doesn't return the expected 0x3357e182 style I was expecting to see for a memory address.I want to do something like print &x
, where x is a C++ int variable for example.How can I do this in Python?
推荐答案
id
是您要使用的方法:将其转换为十六进制:
id
is the method you want to use: to convert it to hex:
hex(id(variable_here))
例如:
x = 4
print hex(id(x))
给我:
0x9cf10c
您想要什么,对吗?
(有趣的是,将两个变量绑定到相同的int
可能会导致使用相同的内存地址.)
试试:
(Fun fact, binding two variables to the same int
may result in the same memory address being used.)
Try:
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))
这给了我相同的对,即使是大整数也是如此.
This gave me identical pairs, even for the large integers.
这篇关于Python变量的打印内存地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!