0

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.

  • As a minor note, you [probably want to use new-style classes](http://stackoverflow.com/questions/54867/what-is-the-difference-between-old-style-and-new-style-classes-in-python), so have `Base` extend `object` with `class Base(object):` – Kevin Ji Jan 04 '17 at 18:42
  • @mc10 Thanks for the comment. I should have specified, I am using python 3, my understanding is that all classes in python 3 are new-style classes which all inherit from object automatically – FShoukry Jan 04 '17 at 18:50
  • @mc10 This is probably Python 3, where there are only new-style classes and all classes implicitly inherit from object. – juanpa.arrivillaga Jan 04 '17 at 18:50
  • @FShoukry Ahh, sounds good. Guess it wouldn't hurt to include it, but it won't change anything then. – Kevin Ji Jan 04 '17 at 18:51
  • A few comments: computing the `methods` in `__init__` won't involve methods that are added dynamically after instantiation. Using a dictionary will overwrite methods of parent classes with a similar name. For comparison it might be better to use `if cls is object`. You could update a class' `methods` attribute with the one from the parent class by using a _metaclass_. Have a look at the implementation of `unittest.TestCase` which executes all instance methods that start with `test_`. – a_guest Jan 04 '17 at 19:06

0 Answers0