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

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

问题描述

您能否取消引用从 id<检索到的变量 id/a> 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.

推荐答案

这是一个基于Tiran"评论(现已删除)的实用函数在博客讨论中@Hophat Abc他自己的答案中的参考资料,适用于 Python 2 和 3.

Here's a utility function based on a (now-deleted) comment made by "Tiran" in a weblog discussion @Hophat Abc references in his own answer that will work in both Python 2 and 3.

免责声明:如果您阅读链接的讨论,您会发现有些人认为这太不安全了,永远不应该使用它(同样在下面的一些评论).我不同意这种评估,但我觉得我至少应该提到关于使用它存在一些争论.

Disclaimer: If you read the the linked discussion, you'll find that some folks think this is so unsafe that it should never be used (as likewise mentioned in some of the comments below). I don't agree with that assessment but feel I should at least mention that there's some debate about using it.

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天全站免登陆