Python 如何提取super()。\uuuu init\uuuu来自的类?
设想一个类Python 如何提取super()。\uuuu init\uuuu来自的类?,python,python-3.x,oop,multiple-inheritance,super,Python,Python 3.x,Oop,Multiple Inheritance,Super,设想一个类MyMixInClass正在多重继承层次结构中使用。当使用super()调用某个方法时,是否有某种方法可以检查或钻取该方法来自的类 例如: class MyMixInClass: def __init__(self): initfunc = getattr(super(), '__init__') # can we figure out which class the __init__ came from? 对于mro序列中的每个类,您可以检查类\uu
MyMixInClass
正在多重继承层次结构中使用。当使用super()
调用某个方法时,是否有某种方法可以检查或钻取该方法来自的类
例如:
class MyMixInClass:
def __init__(self):
initfunc = getattr(super(), '__init__')
# can we figure out which class the __init__ came from?
对于mro序列中的每个类,您可以检查类
\uu dict\uu
中是否有\uuu init\uuu
方法:
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')
输出:
在这个输出中,具有
\uuuu init\uuuu
方法的第一个类(这里B
)是由super()调用的类。D()
调用mro
中的mro
调用MyMixInClass
@ReblochonMasque的一个不准确的实例。mro
中的下一个类可能没有\uuuu init\uuuu
方法是,mro
返回祖先列表;您可以对它们是否具有init进行排序。@ReblochonMasque您可以通过一个多重继承示例来说明这一点,其中只有一些类具有\uuuu init\uuuu
方法吗?
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