repr(object): Return a string containing a printable representation of an object. This is the same value yielded by conversions (reverse quotes). It is sometimes useful to be able to access this operation as an ordinary function. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__() method.
这在Python documentation中有很好的解释:
所以您在这里看到的是^{} 的默认实现,它对于序列化和调试非常有用。
__repr__
应该返回对象的可打印表示,很可能是创建此对象的方法之一。见官方文件here。__repr__
更适合开发人员,而__str__
则适合最终用户。一个简单的例子:
独立Python解释器使用
__repr__
以可打印格式显示类。示例:在类中未定义
__str__
方法的情况下,它将调用__repr__
函数,试图创建可打印的表示。此外,默认情况下,类的
print()
将调用__str__
。Documentation如果你愿意的话
相关问题 更多 >
编程相关推荐