python变量地址,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 is the method you want to use: to convert it to hex:

hex(id(variable_here))

For instance:

x = 4

print hex(id(x))

Gave me:

0x9cf10c

Which is what you want, right?

(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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值