Allowing the repr() of my class's instances to be parsed by eval()

南笙酒味 提交于 2019-12-06 08:31:28

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)

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

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

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