【问题标题】:When running a method from a Python superclass, how can I know the name of the child class that invoked it?从 Python 超类运行方法时,我如何知道调用它的子类的名称?
【发布时间】:2014-07-04 05:49:00
【问题描述】:

假设我有这个父类:

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 类:

class MyTestCase(BaseTestCase):

    @classmethod
    def setUpClass(cls):
        # Call SetUpClass from parent (BaseTestCase)
        super(cls, cls).setUpClass()
        # Do more stuff...

因为许多类可以从同一个父类继承。如何知道在给定时间内调用父类的类的名称?

我希望我的问题有意义。 :S

【问题讨论】:

    标签: python oop inheritance superclass


    【解决方案1】:

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

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

    请注意,您应该使用super(cls, cls)!如果您要从MyTestCase 创建派生类,那将导致infinite recursion!始终使用实际的类:

    class MyTestCase(BaseTestCase):
        @classmethod
        def setUpClass(cls):
            # Call SetUpClass from parent (BaseTestCase)
            super(MyTestCase, cls).setUpClass()
            # Do more stuff...
    

    演示:

    >>> 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
    

    【讨论】:

      猜你喜欢
      • 2013-05-25
      • 2011-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      相关资源
      最近更新 更多