2

I am attempting to create a method in a base class that allows all subclasses to access the name of the direct parent class from which they inherit. The following code does not work, but how could I implement something similar to this?

class A:
    def get_parent_name(self):
        return super().__name__

class B(A):
    pass

class C(B):
    pass

C.get_parent_name()

# Expected output: 'B'

I apologise in advance if this is not a well phrased question. This is my first time posting on Stack Overflow so any advice to improve my questions would also be appreciated

  • Does this answer your question? [Get parent class name?](https://stackoverflow.com/questions/10091957/get-parent-class-name) – Vishwa Mittar Apr 22 '22 at 07:02

2 Answers2

2

You can use C.__mro__ or C.mro().

Kang San Lee
  • 312
  • 2
  • 10
0

Here's a complete example based on your three classes:

class A:
    def __init__(self):
        pass
    def parent(self):
        return self.__class__.__bases__[0]

class B(A):
    def __init__(self):
        super(B, self).__init__()

class C(B):
    def __init__(self):
        super(C, self).__init__()

print(A().parent())
print(B().parent())
print(C().parent())

Output:

<class 'object'>
<class '__main__.A'>
<class '__main__.B'>
DarkKnight
  • 19,739
  • 3
  • 6
  • 22