Python线性继承,中子类在super()属性调用中被子类覆盖

时间:2020-09-28 22:21:42

标签: python python-3.x inheritance properties

我有这样的课程设置:

class A(object):
   __configuration = {}
   def __init__(self, configuration: dict = {}):
      A.__configuration = configuration
   
   @property
   def configuration(self):
      return A.__configuration

class B(A):
   def __init__(self, configuration: dict = {}):
      super().__init__(configuration=configuration)
   @property
   def configuration(self):
      return super().configuration.get('mammals')

class C(B):
   def __init__(self, configuration: dict = {}):
      super().__init__(configuration=configuration)
   @property
   def configuration(self):
      return super().configuration.get('human')

现在这是我遇到无法解决的问题的地方。

当我实例化C类时,它将调用Super Init到B类。然后,B类又将Super Init调用到A类。

该配置将被设置为A类中的一个类变量,而调用时的property方法将返回该configuration / dict / class变量。

B类,我正在尝试使配置属性获得超级(A类的)配置,然后从中检索“哺乳动物”值。

然后,C类又试图(当从C类调用时)从其父类获取“人类”值,该值将称为B类的属性,而我希望又将其称为A类的属性。 。因此导致键/值查找:

  1. 获取整个配置
  2. 获取哺乳动物的值(这是另一个配置/字典)
  3. 获取人的价值(类型无关紧要)

问题: 当我实例化类C时,它应在实例化时传播到类A。 A类的配置设置正确。然后,在类B中,当我引用super()。configuration时,它最终返回我的CHILD(类C)的配置。

例如,如果我将此行放在B类的 init 中,并从C类实例进行实例化:

打印(自我配置) 它会返回给我人类词典的值,而不是我想要的哺乳动物词典的值。


这是我在实例化C类时传递的配置示例:

config = {
   'mammals': {
      'human': {
         ...
      }
      ...
   }
   ...
}
exampleInstantiation = C(configuration=config)

我一直在尝试查找线性继承,即类方法的解析顺序,但是我找不到任何让我了解为什么子类重写MIDDLE类的东西。

感谢您的帮助。

0 个答案:

没有答案
相关问题