How to access variable by id? [duplicate]

岁酱吖の 提交于 2019-11-28 04:16:01

问题


Possible Duplicate:
Get object by id()?

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

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

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: Also would be interesting to know, how to change value of var.


回答1:


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



来源:https://stackoverflow.com/questions/14257350/how-to-access-variable-by-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!