<p>关于python3,您有两个失败的测试。你知道吗</p>
<pre><code>======================================================================
FAIL: test_equality_and_inequality (test_point.PointTests)
Traceback (most recent call last):
File "/home/josef/tmp/deleteme/test_point.py", line 29, in test_equality_and_inequality
self.assertEqual(Point(1, 2, 3), Point(1, 2, 3))
AssertionError: <point.Point object at 0x7f7a20cff050> != <point.Point object at 0x7f7a20cff090>
</code></pre>
<p>发生这种情况是因为声明新对象的返回是具有唯一id的对象本身。计算<code>Point(1, 2, 3)</code>会返回一个唯一的东西,如<code><point.Point object at 0x7f7a20cff050></code>,而不是类本身。因此,如果实例化一个类的两个实例,它们必然是不同的。你知道吗</p>
<pre><code>======================================================================
FAIL: test_string_representation (test_point.PointTests)
Traceback (most recent call last):
File "/home/josef/tmp/deleteme/test_point.py", line 19, in test_string_representation
self.assertEqual(repr(point), 'Point(x=1, y=2, z=3)')
AssertionError: '<point.Point object at 0x7f7a20d75f90>' != 'Point(x=1, y=2, z=3)'
- <point.Point object at 0x7f7a20d75f90>
+ Point(x=1, y=2, z=3)
</code></pre>
<p>Python类可以有<code>__str__</code>方法和<code>__repr__</code>方法。前者主要用于返回对象的字符串表示形式,因此如果您将其显示给人类,则会得到一些看起来不错的东西。我认为后者使用较少(我仍然通常定义它),但据我所知,它应该启用“对象到表示到对象”的往返;以这样一种方式显示实例:理论上,您可以<code>eval()</code>该字符串表示并忠实地再现对象。你知道吗</p>
<p>您的类定义没有<code>__repr__</code>,因此测试当然会失败。有时(对于较大的值有时)如果我懒惰,我会这样做:</p>
<pre class="lang-py prettyprint-override"><code>def __str__(self):
return self.__repr__()
</code></pre>