是否可以使用 assert_equal 来比较对象?我一直看到这个错误:
AssertionError: <ex49.parser.Sentence object at 0x01F1BAF0> !=
<ex49.parser.Sentence object at 0x01F1BB10>
相关代码片段:
def test_parse_subject():
testsentence = "princess go east"
result = lexicon.scan(testsentence)
Sent = parse_sentence(result)
ResultSent = Sentence(('subject', 'princess'),
('verb', 'go'),
('object', 'east'))
print ResultSent.subject
print ResultSent.verb
print ResultSent.object
print Sent.subject
print Sent.verb
print Sent.object
assert_equal(Sent, ResultSent)
屏幕上的打印输出表明对象具有相同的内容 - 但出现断言错误。为什么是这样?有什么方法可以使用 assert_equal 来覆盖它吗?
最佳答案
我相信您需要在 Sentence 类上实现 __eq__ 方法。
assertEqual(first, second, msg=None)¶ Test that first and second are equal. If the values do not compare equal, the test will fail.
In addition, if first and second are the exact same type and one of list, tuple, dict, set, frozenset or unicode or any type that a subclass registers with addTypeEqualityFunc() the type-specific equality function will be called in order to generate a more useful default error message (see also the list of type-specific methods).
The correspondence between operator symbols and method names is as follows: xlt(y), x<=y calls x.le(y), x==y calls x.eq(y), x!=y and x<>y call x.ne(y), x>y calls x.gt(y), and x>=y calls x.ge(y).
Python data model documentation
一个例子:
import unittest
class A:
def __init__(self, num):
self.num = num
def __eq__(self, other):
return self.num == other.num
class Test(unittest.TestCase):
def test(self):
a1 = A(1)
a12 = A(1)
a2 = A(2)
self.assertEqual(a1, a1, 'a1 != a1')
self.assertEqual(a1, a12, 'a1 != a12')
self.assertEqual(a1, a2, 'a1 != a2')
def main():
unittest.TestRunner(Test())
if __name__ == '__main__':
unittest.main()
现在评论 __eq__ 方法并查看差异。
关于python - 艰难地学习 Python,Ex 49 : Comparing objects using assert_equal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9306242/