我想比较类的 __repr__ 与 float 或整数。
class TestClass:
def __init__(self, a = 5):
self.a = a
def __repr__(self):
return self.a
这显然会返回错误,因为 a 不是 string:
TypeError: __repr__ returned non-string (type int)
如果我将它设置为字符串,则打印是正确的:
>>> TestClass()
5
但打印品没有可比性:
>>> TestClass() == 5
False
我应该使用什么来比较类返回值以使其 TestClass() == 5 与 True?
请您参考如下方法:
都没有。
__repr__ 仅在您需要字符串并获取对象的情况下调用,例如来自 print 或作为命令行上的单个表达式,并且意味着作为一个对象的人类可读表示,它(希望)可以从中重建。
回想一下,在不重载 __repr__ 的情况下,您从命令行获得的是一个表示身份 的字符串,而不是值,对象的,例如:
<__main__.TestClass at 0x20feb8836d8>
另一方面,您对 TestClass() == 5 所做的是值比较。
因此,如果您定义了 __eq__,它只会评估为 True,相等方法:
class TestClass:
def __init__(self, a = 5):
self.a = a
def __eq__(self, other):
return self.a == other
print(TestClass() == 5)
输出:
True
