继承unittest后,__init__方法报错:TypeError: __init__() takes 1 positional argument but 2 were given

最初代码报错

最开始的代码为:

import unittest
class TestCase(unittest.TestCase):
    def __init__(self):
        self.test='test'
    def test_test(self):
        print('1')
if __name__ == '__main__':
    unittest.main()
        

执行后,报错

TypeError: __init__() takes 1 positional argument but 2 were given

原因分析:

在子类中加了__init__是重写了父类的初始化方法。
父类的def init(self, methodName=‘runTest’):是传了2个参数,而我传了1个值,
父类方法:

    def __init__(self, methodName='runTest'):
        """Create an instance of the class that will use the named test
           method when executed. Raises a ValueError if the instance does
           not have a method with the specified name.
        """
        self._testMethodName = methodName
        self._outcome = None
        self._testMethodDoc = 'No test'
        try:
            testMethod = getattr(self, methodName)
        except AttributeError:
            if methodName != 'runTest':
                # we allow instantiation with no explicit method name
                # but not an *incorrect* or missing method name
                raise ValueError("no such test method in %s: %s" %
                      (self.__class__, methodName))
        else:
            self._testMethodDoc = testMethod.__doc__
        self._cleanups = []
        self._subtest = None

        # Map types to custom assertEqual functions that will compare
        # instances of said type in more detail to generate a more useful
        # error message.
        self._type_equality_funcs = {}
        self.addTypeEqualityFunc(dict, 'assertDictEqual')
        self.addTypeEqualityFunc(list, 'assertListEqual')
        self.addTypeEqualityFunc(tuple, 'assertTupleEqual')
        self.addTypeEqualityFunc(set, 'assertSetEqual')
        self.addTypeEqualityFunc(frozenset, 'assertSetEqual')
        self.addTypeEqualityFunc(str, 'assertMultiLineEqual')

解决办法:

在__init__参数中添加method=‘runtest’,在__init__方法内添加:super(TestCase,self).init(methodName)

class TestCase():
    def __init__(self,methodName='runTest'):
    	super(TestCase,self).__init__(methodName)
    def test_test(self):
        print('1')
if __name__ == '__main__':
    unittest.main()

你可能感兴趣的:(Python)