When running a method from a Python superclass, how can I know the name of the child class that invoked it?

StackOverflow https://stackoverflow.com/questions/23684026

Pergunta

Let's say I have this parent class:

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

And I have this class that inherits from the BaseTestCase class above:

class MyTestCase(BaseTestCase):

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

Since many classes can inherit from the same parent class. How can I know the name of the class that invoked the parent class in a given time?

I hope my question make sense. :S

Foi útil?

Solução

cls.__name__ is always the name of the current class, because cls is bound the actual class object on which the class method was called.

In other words, cls is not a reference to the class on which the method is defined.

Note that you should not use super(cls, cls)! That'll lead to infinite recursion if you were to create a derived class from MyTestCase! Use the actual class, always:

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

Demo:

>>> 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
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top