When running a method from a Python superclass, how can I know the name of the child class that invoked it?
假设我有这个父类:
1 2 3 4 5 6 7 8 | class BaseTestCase(unittest.TestCase): @classmethod def setUpClass(cls): # I want to assign the name of the class that called # the super class in a variable. cls.child_class_name = ?? # Do some more stuff... |
我有一个从上面的basetestcase类继承的类:
1 2 3 4 5 6 7 | class MyTestCase(BaseTestCase): @classmethod def setUpClass(cls): # Call SetUpClass from parent (BaseTestCase) super(cls, cls).setUpClass() # Do more stuff... |
因为许多类可以从同一父类继承。如何知道在给定时间内调用父类的类的名称?
我希望我的问题讲得通。的S
换句话说,
注意不要使用
1 2 3 4 5 6 | class MyTestCase(BaseTestCase): @classmethod def setUpClass(cls): # Call SetUpClass from parent (BaseTestCase) super(MyTestCase, cls).setUpClass() # Do more stuff... |
演示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | >>> class Foo(object): ... @classmethod ... def spam(cls): ... print(cls.__name__) ... >>> class Bar(Foo): ... @classmethod ... def spam(cls): ... super(Bar, cls).spam() ... >>> Bar.spam() Bar >>> Foo.spam() Foo |