是否可以取消引用变量ID? [英] Is it possible to dereference variable id's?

查看:81
本文介绍了是否可以取消引用变量ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以取消引用从 id 函数Python?例如:

Can you dereference a variable id retrieved from the id function in Python? For example:

dereference(id(a)) == a

我想从学术角度了解;我知道还有更实用的方法.

I want to know from an academic standpoint; I understand that there are more practical methods.

推荐答案

这是一个基于中引用 a>在Python 2和3中均可使用

Here's a utility function based on a comment made by "Tiran" in the discussion Hophat Abc referenced that will work in both Python 2 and 3:

import _ctypes

def di(obj_id):
    """ Inverse of id() function. """
    return _ctypes.PyObj_FromPtr(obj_id)

if __name__ == '__main__':
    a = 42
    b = 'answer'
    print(di(id(a)))  # -> 42
    print(di(id(b)))  # -> answer

这篇关于是否可以取消引用变量ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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