简体   繁体   English

从文本表示重构Python对象

[英]Reconstructing Python objects from text representation

Is it possible to create an object from the represented text of python objects when they are repr esented on the screen? 是否有可能时,他们创建一个从Python对象的表示的文本对象repr屏幕上esented?

>>> select.select([s], [],[])
([<socket._socketobject object at 0x7f274914c600>], [], [])
>>> eval('<socket._socketobject object at 0x7f274914c600>') # Fail

Or once the object is represented to stdout, does it get GCd? 或者一旦将对象表示为stdout,它是否会获得GCd?

Not of significant use, but when playing with the Python CLI, it might be occasionally helpful. 没有多大用处,但在使用Python CLI时,它可能偶尔会有所帮助。

The output of repr may be able to reconstruct the object, however the convention is, if it has bits surrounded by angle brackets then those bits aren't reconstructible. repr的输出可能能够重建对象,但是约定是,如果它具有由尖括号包围的位,则那些位不可重构。

So in this case you can't reconstruct the socket, and yes it will be garbage collected straight away. 所以在这种情况下你无法重建套接字,是的,它将立即被垃圾收集。

It is not, as apparently text presentation does not necessarily contain all information of the object. 它不是,因为显然文本表示不一定包含对象的所有信息。

If you want to text-like object representation try JSON module. 如果你想要类似文本的对象表示,请尝试使用JSON模块。

http://docs.python.org/library/json.html?highlight=json#json http://docs.python.org/library/json.html?highlight=json#json

Also please note that objects encapsulated in this presentation cannot have native object bindings, like sockets, file handles, etc. 另请注意,封装在此演示文稿中的对象不能具有本机对象绑定,如套接字,文件句柄等。

You are encouraged to create objects for which the repr allows you to create a new object by pasting the repr output, but it is not strictly enforced. 建议您创建repr允许您通过粘贴repr输出来创建新对象的对象,但不会严格执行。 Depending on the nature of the object and any internals, this also might not be something that is easy to do. 根据对象的性质和任何内部结构,这也可能不容易做到。

There are many ways to do it. 有很多方法可以做到这一点。 Here is a very simple example of one way: 这是一个非常简单的例子:

class ReprObject(object):
    def __init__(self, value, item):
        self.value = value
        self.item = item

    def __repr__(self):
        return '%s(**%r)' % (self.__class__.__name__, self.__dict__)

So then we take that to the interactive interpreter and create an instance: 那么我们将它带到交互式解释器并创建一个实例:

>>> r = ReprObject(value=1, item=True)
>>> r
ReprObject(**{'item': True, 'value': 1})

Now copy/paste that repr and use it to create a new object: 现在复制/粘贴该repr并使用它来创建一个新对象:

>>> r2 = ReprObject(**{'item': True, 'value': 1})
>>> r2
ReprObject(**{'item': True, 'value': 1})

And eval() would also work: 并且eval()也可以工作:

>>> eval(repr(r2))
ReprObject(**{'item': True, 'value': 1})

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

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