在Python中调用所有具有多重继承的实例方法

时间:2017-01-04 18:41:08

标签: python oop inheritance multiple-inheritance instance-methods

我正在尝试创建一组类作为模块化逻辑块的容器。我们的想法是能够通过继承(可能是多重继承)来混合和匹配类,以执行这些模块化逻辑的任意组合。这是我目前的结构:

class Base:
    methods = {}

    def __init__(self):
      """
      This will create an instance attribute copy of the combined dict
      of all the methods in every parent class.
      """
      self.methods = {}
      for cls in self.__class__.__mro__:
      # object is the only class that won't have a methods attribute  
      if not cls == object:
          self.methods.update(cls.methods)


    def call(self):
      """
      This will execute all the methods in every parent
      """
      for k,v in self.methods.items():
        v(self)


class ParentA(Base):

    def method1(self):
        print("Parent A called")

    methods = {"method":method1}

class ParentB(Base):

    def method2(self):
        print("Parent B called")

    methods = {"method2" : method2}

class Child(ParentA, ParentB):

    def method3(self):
        print("Child called")

    methods = {"method3" : method3}

这似乎按预期工作但我想知道是否有任何我可能会缺少设计明智或者如果有什么我想做的事情我不应该这样做。对结构的任何考虑或反馈都是非常受欢迎的。以及如何使这更加pythonic的提示。提前谢谢大家。

0 个答案:

没有答案