[英]Python unittest setUpClass cannot call method from base class
I am using the unittest framework from Python, and run into issues when setting up a class for a test case.我正在使用 Python 中的 unittest 框架,并在为测试用例设置类时遇到问题。 I would like to call a method from the base class in the setUpClass() method as follows:
我想从 setUpClass() 方法中的基类调用一个方法,如下所示:
class TestA(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(TestA, self).__init__(*args, **kwargs)
self.variable = "hello"
def do_something(self):
print(self.variable)
return self.variable
class TestB(TestA.TestA):
@classmethod
def setUpClass(cls):
var = cls.do_something()
But I get an error saying that I cannot call do_something().但是我收到一个错误,说我不能调用 do_something()。
TypeError: unbound method do_something() must be called with TestB instance as first argument (got nothing instead)
I have no idea how (and if) I can call a method from the base class as part of the setUpClass method.我不知道如何(以及是否)可以从基类调用方法作为 setUpClass 方法的一部分。
What am I missing?我错过了什么?
Use super()
.使用
super()
。
>>> class Base:
... def do(self):
... print('base is doing something')
...
>>> class Child(Base):
... def better_do(self):
... super().do()
... print('much better')
...
>>>
>>> c = Child()
>>> c.do()
base is doing something
>>> c.better_do()
base is doing something
much better
>>>
A class method, however, is bit different.然而,类方法有点不同。 You must call the class itself.
您必须调用类本身。
>>> class Base:
... @classmethod
... def cls_do(cls):
... print('Base class is doing something')
...
>>> Base.cls_do()
Base class is doing something
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.