Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cassandra/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何提取super()。\uuuu init\uuuu来自的类?_Python_Python 3.x_Oop_Multiple Inheritance_Super - Fatal编程技术网

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