How to retrieve the names of children classes in the inherited one?
我有一个基类,在创建其他类时继承它。
我想做的一件事是,在
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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() |
此输出
1 2 | hello from one hello from two |
号
有没有办法让
我在考虑以下几点(这只是一个疯狂挥手的例子,展示我想称之为裸
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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() |
无需为此与MRO打交道,只需看看
1 2 3 4 5 6 7 8 9 10 11 12 13 | class Main: def __init__(self): print(f"Hello from {type(self).__name__}!") class Sub(Main): pass class SubSub(Sub): pass Main() Sub() SubSub() |
结果:
1 2 3 | Hello from Main! Hello from Sub! Hello from SubSub! |
。
1 | print(f"hello from {self.__class__}") |
使用inspect.getmro函数
1 2 | import inspect inspect.getmro(Two) |
号