<p>错误发生在</p>
<pre><code>self.assertEqual(repr(point), 'Point(x=1, y=2, z=3)')
</code></pre>
<p>由于您习惯性地只在<code>__Point__</code>上定义了<code>__str__</code>方法,因此<code>__repr__</code>仍然是内置方法,导致类似<code>"point.Point object at 0x7fbd8850b190"</code>的结果。要解决这个问题,请定义<code>Point</code>的<code>__repr__</code>。你知道吗</p>
<p>当您定义<code>__repr__</code>方法时,python使用它作为<code>__str__</code>的默认方法,但它不会反过来做。你知道吗</p>
<p>对于您的(不是很小的)代码示例,这仍然会导致错误</p>
<pre><code>self.assertEqual(Point(1, 2, 3), Point(1, 2, 3))
</code></pre>
<p>这是因为这条线不是测试表示的相等性,而是测试对象的相等性。由于实例化<code>Point</code>两次,因此<code>assertEqual</code>的第一个参数实际上与第二个参数不同,即使它们都是<code>Point</code>的实例,而且它们的实例变量相等。你知道吗</p>
<p>您可以将这些对象理解为类似“双胞胎”或“克隆体”的东西:即使它们的所有属性都相同,它们仍然具有不同的“身份”。你知道吗</p>
<p>如果我们想把“twins”看作“equal”,Python允许我们定义一个由Python用来检查对象相等性的相等关系。我们可以通过实现<code>__eq__</code>方法来定义这一点。很可能你想要的是:</p>
<pre><code>class Point:
def __init__(x, y, z):
self.x = x
self.y = y
self.z = z
def __repr__(self):
return f"Point(x={self.x}, y={self.y}, z={self.z})"
def __eq__(self, other):
return self.__repr__() == other.__repr__()
</code></pre>
<p>阅读Python的“魔术方法”的介绍,例如<a href="https://rszalski.github.io/magicmethods/" rel="nofollow noreferrer">https://rszalski.github.io/magicmethods/</a>,可能是个好主意</p>