Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
假设我自己定义了一个类,并__repr__为它定义了一个方法。我想将它转换回我的对象。我知道对象序列化可能是这样做的好方法(使用json模块)但是无论如何我可以使用内置eval函数来实现这一点?
__repr__
json
eval
编写你的__repr__(),以便它创建一个有效的 Python 表达式来实例化你的对象。
__repr__()
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()。
repr()
你不必定义任何特殊eval()的东西——只要传入你从repr().
eval()