我正在学习Python并尝试测试我用unittest编写的多项式类。似乎我从直接用Python运行测试和使用unittest运行测试得到了不同的结果,但我不明白发生了什么。在
import unittest
from w4_polynomial import Polynomial
class TestPolynomialClass(unittest.TestCase):
def setUp(self):
self.A = Polynomial()
self.A[1] = 1
self.A[2] = 2
self.B = Polynomial()
self.B[1234] = 5678
def test_assertNotEq(self):
self.C = Polynomial()
self.C[1234] = 5678
self.C[1] = 1
self.C[2] = 3
self.assertNotEqual(self.A+self.B, self.C)
if __name__ == '__main__':
unittest.main()
Unittest失败。。。但我不明白为什么。这两个多项式不一样。下面是在python脚本中使用print进行比较的同一测试的结果。多项式不同,但结果相同:
^{pr2}$如果你能帮我解释一下发生了什么事,我将不胜感激。在
抱歉忘记了unittest的错误
FAIL: test_assertEq (__main__.TestPolynomialClass)
----------------------------------------------------------------------
Traenter code hereceback (most recent call last):
File "add.py", line 18, in test_assertEq
self.assertNotEqual(self.A+self.B, self.C)
AssertionError: <w4_polynomial.Polynomial object at 0x7f2d419ec390> == <w4_polynomial.Polynomial object at 0x7f2d419ec358>
现在多项式类:
class Polynomial():
def __init__(self, value=[0]):
self.v = []
self.n = []
temp = list(reversed(value[:]))
if value == [0]:
self[0] = 0
else:
for x in range(0, len(temp)):
self[x] = temp[x]
#self.__compress()
...
def __eq__(self, value):
temp1 = self.v[:]
temp2 = self.n[:]
temp3 = value.v[:]
temp4 = value.n[:]
temp1.sort()
temp2.sort()
temp3.sort()
temp4.sort()
return (temp1 == temp3 and temp2 == temp4)
def __ne__(self, value):
temp1 = self.v[:]
temp2 = self.n[:]
temp3 = value.v[:]
temp4 = value.n[:]
temp1.sort()
temp2.sort()
temp3.sort()
temp4.sort()
return (temp1 != temp3 and temp2 != temp4)
...
def main():
pass
if __name__=="__main__":
main()
我认为问题在于多项式类中
def __ne__
函数的实现。 调用assertNotEqual时,当传递的值不相等时,应为真值。但是在这个类中,您直接发送temp1的输出!=温度3和温度2!=温度4。在所以,函数应该是这样的
相关问题 更多 >
编程相关推荐