1

这是__repr__一个名为的类中的方法Grid

def __repr__(self):
    return 'Grid(%r, %r)' % (self.rows, self.cols)

unittest我已经在一个模块中放置了一些基本测试,以检查是否eval可以在没有失败的情况下进行相等测试,看起来像这样:

# One of the tests inside a unittest.TestCase subclass
def test_grid(self):
    grid = Grid(3, 4)
    self.assertEqual(eval(repr(grid)), grid)

现在,这是测试报告(我已将此测试与其他测试分开):

======================================================================
FAIL: test_grid (tests.test_core.TestCore)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/user/Desktop/sample/tests/test_core.py", line 14, in test_grid
    self.assertEqual(eval(repr(grid)), grid)
AssertionError: Grid(3, 4) != Grid(3, 4)

----------------------------------------------------------------------
Ran 1 test in 0.003s

FAILED (failures=1)

断言异常消息让我更加困惑。不Grid(3, 4) != Grid(3, 4)应该是False吗?

4

1 回答 1

3

我认为问题的核心是您正在创建一个新对象,即使内部值相同 - python 也无法判断它们是否相同,因此它通过引用比较对象。他们是不同的。我相信您需要覆盖 python 的魔术比较运算符才能通过内部值进行比较。

于 2014-11-13T17:11:54.950 回答