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

1

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.