允许我的类实例的repr()由eval()解析 [英] Allowing the repr() of my class's instances to be parsed by eval()

查看:79
本文介绍了允许我的类实例的repr()由eval()解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我自己定义了一个类,并为此定义了一个__repr__方法.我想将其转换回我的对象​​.我知道对象序列化可能是这样做的一种好方法(使用json模块),但是无论如何,我可以使用内置的eval函数来实现这一点吗?

Say I have defined a class myself and I defined a __repr__ method for it. I want to about convert it back to my object. I know that object serialization may be a good way of doing so (using the json module) but is there anyway I can use the built-in eval function to achieve this?

推荐答案

编写您的__repr__(),以便它创建用于实例化对象的有效Python表达式.

Write your __repr__() so it creates a valid Python expression for instantiating your object.

class MyClass(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b
    def __repr__(self):
        return "%s(%r, %r)" % (type(self).__name__, self.a, self.b)

显然,这取决于您使用的具有自己合理的repr()的值.

Obviously this relies on the values you're using having their own reasonable repr().

您不必定义任何特殊的eval()-只需传入从repr()中获得的任何内容即可.

You don't have to define any special eval()—just pass in whatever you get from repr().

这篇关于允许我的类实例的repr()由eval()解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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