当前位置: 代码迷 >> python >> AttributeError:“ ...”对象没有属性“ _type_equality_funcs”
  详细解决方案

AttributeError:“ ...”对象没有属性“ _type_equality_funcs”

热度:109   发布时间:2023-07-14 08:58:55.0

我正在尝试使用Python的unittest模块来比较结果和期望值,并最终获得测试统计信息。 但是,下面的示例代码给我以下错误:

File "...", line 16, in <module>
  run_tests.test_equal()
File "...", line 13, in test_equal
  self.assertEqual(self.result, self.expected)
File "/usr/lib/python2.7/unittest/case.py", line 512, in assertEqual
  assertion_func = self._getAssertEqualityFunc(first, second)
File "/usr/lib/python2.7/unittest/case.py", line 493, in _getAssertEqualityFunc
  asserter = self._type_equality_funcs.get(type(first))
AttributeError: 'RunTests' object has no attribute '_type_equality_funcs'

样例代码:

import unittest

class RunTests(unittest.TestCase):
   def __init__(self, result, expected):
      self.result = result
      self.expected = expected

   def runTest(self):
      test_equal(self)

   def test_equal(self):
      self.assertEqual(self.result, self.expected)

run_tests = RunTests(9, 9)
run_tests.test_equal()

if __name__ == '__main__':
   unittest.main()

如何在不同的输入值上使用模块的比较功能? 我找到了 ,但是问题似乎有所不同。

非常感谢。

您跳过了RunTests.__init__内部基类的__init__的调用,该调用负责定义_type_equality_funcs

def __init__(self, result, expected):
      super().__init__()
      self.result = result
      self.expected = expected

您需要调用基类的__init__方法。 这可能是有用的:

    import unittest
    class RunTests(unittest.TestCase):
       def __init__(self, *args, **kwargs):
          super(RunTests, self).__init__()

       def runTest(self):
          self.test_equal()

       def test_equal(self):
          self.assertEqual(9, 9)

    run_tests = RunTests()
    run_tests.test_equal()

    if __name__ == '__main__':
       unittest.main() 
  相关解决方案