如何提取super().__ init__来自的类?

想象一下在多继承层次结构中使用的类MyMixInClass。 当使用super()调用某个方法时,是否有某种方法可以检查或钻取以提取此方法来自的类?

class MyMixInClass: def __init__(self): initfunc = getattr(super(), '__init__') # can we figure out which class the __init__ came from?


For each class in the mro sequence, you can check if there is an __init__ method in the class __dict__:

class A:
    def __init__(self): pass class B(A): def __init__(self): super().__init__() class C(A): pass class D(B, C): pass if __name__ == '__main__': for cls in D.__mro__: if '__init__' in cls.__dict__: print(f'{cls.__name__} has its own init method', end='\n') else: print(f'{cls.__name__} has no init method', end='\n')

output:

D has no init method
B has its own init method
C has no init method
A has its own init method
object has its own init method

In this output, the first class having an __init__ method (here B), is the one called by super().__init__() in D()

猜你喜欢

转载自www.cnblogs.com/gamecenter/p/11096014.html