Python变量的打印内存地址 [英] print memory address of Python variable

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

问题描述

如何在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变量的打印内存地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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