继承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()
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值