如何通过ID访问变量? [英] How to access variable by 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屋!