如何通过ID访问变量? [英] How to access variable by id?

查看:100
本文介绍了如何通过ID访问变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
通过id()获取对象?

Possible Duplicate:
Get object by id()?

>>> var = 'I need to be accessed by id!'
>>> address = id(var)
>>> print(address)
33003240

是否可以使用内存中由id()提供的var地址访问var的值?

Is there any way to use address of var in memory, provided by id(), for accessing value of var?

UPD:
我还想说,如果不能通过标准的Python做到这一点,那么如果可以通过破解Python的C ++内部实现这一点,那也将很有趣.

UPD:
I also want to say, that if this cannot be done in standard Python, it also would be interesting, if this somehow could be implemented via hacking C++ internals of Python.

UPD2: 知道如何更改 var的值也很有趣.

UPD2: Also would be interesting to know, how to change value of var.

推荐答案

仅针对您的情况,解决方案是:

A solution, only for your case, would be:

var = 'I need to be accessed by id!'
address = id(var)
print(address)
var2 = [x for x in globals().values() if id(x)==address]

它也可以在类似的函数内部工作

It also works from inside a function like

def get_by_address(address):
    return [x for x in globals().values() if id(x)==address]

var = 'I need to be accessed by id!'
address = id(var)
print(address)
var2 = get_by_address(address)

但是正如其他人指出的那样:首先请确保没有更好的解决方案可以更好地满足您的需求

But as others pointed out: First make sure there is no better solution that better fits your needs

这篇关于如何通过ID访问变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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