简体   繁体   English

我们如何从字符串中获取对象引用? 这样的字符串必须包含哪些信息?

[英]How can we get an object reference from a string? What information must such a string contain?

Suppose we have a string, such as <dict object at 0x0000000000511948> . 假设我们有一个字符串,例如<dict object at 0x0000000000511948> How would we then get a reference to the object from that string? 然后,我们如何从该字符串获取对该对象的引用? If the example given does not contain sufficient information to get a reference to the object, I am willing to change the string. 如果给出的示例没有足够的信息来获取对该对象的引用,我愿意更改该字符串。

Basically, we are seeking two functions obj2str and str2obj such that the following test returns clear: 基本上,我们正在寻找两个函数obj2strstr2obj ,以使以下测试返回清晰:

def single_test(obj):
    try:
        assert (str2obj(obj2str(obj)) is obj)
        print('things went well')
        return 0
    except (BaseException, Exception) as exep:
        print('test failed')
        if isinstance(exep, AssertionError) and 'str2obj(obj2str(obj))' in str(exep):
            return 1
        return 999

It seems like a good candidate for obj2str would be as follows: 似乎obj2str一个很好的候选者如下:

def obj2str(obj):
    # ignores overridden __repr__ if it is overridden
    return object.__repr__(obj)

However, I don't know what we might do for str2obj 但是,我不知道该如何处理str2obj

In short what you are asking for is impossible. 简而言之,您要的是不可能的。

The string like <dict object at 0x0000000000511948> actually tell you the address of the object in the memory. <dict object at 0x0000000000511948>这样的字符串实际上告诉您对象在内存中的地址。 but python is very very high level programming language, so you cannot access the memory (RAM) directly, even if you have the exact address (like in C), all the more you cannot modify the address. 但是python是非常高级的编程语言,因此,即使您具有准确的地址(如C语言),也无法直接访问内存(RAM),而且您无法修改地址。

But if you want to use something like this you can simply create a new variable referencing your object instead of the string. 但是,如果您想使用类似这样的方法,则可以简单地创建一个引用对象而不是字符串的新变量。

your_dict = {'a':5}
new_dict = your_dict
new_dict['a'] = 17
print(your_dict['a'])
$17

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM