WoJ
WoJ

Reputation: 29987

How to retrieve the names of children classes in the inherited one?

I have a base class which I inherit from when creating other classes.

One of the things I would like to do is, at __init__() time, to log the parent class the object is instantied from. Today I do it the explicit way:

class Main:
    def __init__(self, src):
        print(f"hello from {src}")

class One(Main):
    def __init__(self):
        super().__init__("one")

class Two(Main):
    def __init__(self):
        super().__init__("two")

One()
Two()

This outputs

hello from one
hello from two

Is there a way for Main to know which class ultimately instantiated the object?

I am thinking of something along the lines of (this is just a wildly hand-waving example, to show what that I would like to call bare a bare __init__ instead of also passing a descriptive parameter as in the code above)

class Main:
    def __init__(self, src):
        wherefrom = something_which_holds_the_class_hierarchy[1].__name__ # index 1 = one class above this one
        print(f"hello from {wherefrom}")

class One(Main):
    def __init__(self):
        super().__init__()

class Two(Main):
    def __init__(self):
        super().__init__()

One()
Two()

Upvotes: 0

Views: 51

Answers (3)

ash
ash

Reputation: 5529

No need for messing with MROs for this, just look at type(self):

class Main:
    def __init__(self):
        print(f"Hello from {type(self).__name__}!")

class Sub(Main):
    pass

class SubSub(Sub):
    pass

Main()
Sub()
SubSub()

results in:

Hello from Main!
Hello from Sub!
Hello from SubSub!

self.__class__ is equivalent to type(self), you can use either.

Upvotes: 1

user1443098
user1443098

Reputation: 7645

use inspect.getmro function

import inspect
inspect.getmro(Two)

Upvotes: 0

Alex Hall
Alex Hall

Reputation: 36023

print(f"hello from {self.__class__}")

Upvotes: 1

Related Questions