Search code examples
pythonpython-3.xabstract-classmultiple-inheritance

Dynamic switching between classes which contain similar functions


I have a base abstract class and 2 child classes ( Reader_a and Writer_a) . I have another set of classes (reader_b,writer_b) which inherit from same base class. writer_a writer_b and reader_a and reader_b serve same purpose but handle different type of images, basically they have different backends. Is there any functionality in python by which i can switch these classes based on what Image type user inputs?


Solution

  • I'd add two factory (static) methods to the base class that would check the type and would create the right child class accordingly.

    class Base:
        @staticmethod
        def create_reader(image):
            if image == 'A':
                return Reader_a()
            elif image == 'B':
                return Reader_b()
            else:
                raise Exception('Unknown image')
    
        @staticmethod
        def create_writer(image):
            if image == 'A':
                return Writer_a()
            elif image == 'B':
                return Writer_b()
            else:
                raise Exception('Unknown image')