Calling all instance methods with multiple inheritance in Python

144 views Asked by At

I am trying to create a set of classes as containers of modular blocks of logic. The idea is to be able to mix and match the classes through inheritance (possibly multiple inheritance) to execute any combination of those pieces of modular logic. Here is the structure I currently have:

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}

This seems to work as expected but I was wondering if there is anything I might be missing design wise or if there is something I am trying to do that I should not be doing. Any considerations or feedback on the structure is very welcome. As well as tips on how I could make this more pythonic. Thank you all in advance.

0

There are 0 answers