以艰难的方式学习 Python,例 49:使用 assert_equal 比较对象 [英] Learn Python the Hard Way, Ex 49 : Comparing objects using assert_equal
问题描述
是否可以使用 assert_equal 来比较对象?我一直看到这个错误:
Is it possible to use assert_equal to compare objects? I keep seeing this error:
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 来覆盖它?
The print outputs on screen suggests that the objects have the same contents - yet the assertion error shows up. Why is this? Is there some way to use assert_equal to override this?
推荐答案
我相信你需要在 Sentence 类上实现 __eq__ 方法.
I believe you need to implement the __eq__ method on the Sentence class.
assertEqual(first, second, msg=None)¶测试 first 和 second 是否相等.如果比较的值不相等,则测试将失败.
assertEqual(first, second, msg=None)¶ Test that first and second are equal. If the values do not compare equal, the test will fail.
此外,如果 first 和 second 是完全相同的类型,并且是 list、tuple、dict、set、frozenset 或 unicode 中的一个或子类向 addTypeEqualityFunc() 注册的任何类型,则将调用特定于类型的相等函数以生成更有用的默认错误消息(另请参阅特定于类型的方法列表).
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).
操作符和方法名的对应关系如下:xlt(y),x<=y调用x.le(y),x==y调用x.eq(y), x!=y 和 x<>y 调用 x.ne(y), x>y 调用 x.gt(y),并且 x>=y 调用 x.ge(y).
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).
示例:
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__ 方法并查看不同之处.
Now comment the __eq__ method and see the difference.
这篇关于以艰难的方式学习 Python,例 49:使用 assert_equal 比较对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!