【问题标题】:how to extract the class that super().__init__ comes from?如何提取 super().__init__ 来自的类?
【发布时间】:2019-11-05 20:56:17
【问题描述】:

想象一个在多重继承层次结构中使用的类MyMixInClass。当使用super()调用某个方法时,有没有办法检查或钻取来提取该方法来自的类?

示例:

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

【问题讨论】:

  • MyMixInClass 的实例上调用 mro
  • @ReblochonMasque 不准确。 mro 中的下一个类可能没有 __init__ 方法
  • 是的,mro 返回一个祖先列表;如果他们有初始化,你可以排序。
  • @ReblochonMasque 你能用一个只有一些类有__init__ 方法的多重继承示例来证明这一点吗?

标签: python python-3.x oop multiple-inheritance super


【解决方案1】:

对于mro序列中的每个类,可以检查__dict__类中是否有__init__方法:

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')

输出:

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

在此输出中,具有__init__ 方法(此处为B)的第一个类是super().__init__()D() 中调用的类

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-30
    • 2015-12-06
    • 1970-01-01
    • 2011-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-12
    相关资源
    最近更新 更多