关于oop:从python超类superclass运行方法时,如何知道调用它的子类的名称?

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


cls.__name__始终是当前类的名称,因为cls绑定了调用类方法的实际类对象。

换句话说,cls不是对定义方法的类的引用。

注意不要使用super(cls, cls)!如果要从MyTestCase创建派生类,这将导致无限递归!使用实际类,始终:

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