Search code examples
pythonclassswitch-statement

Create almost similar classes based on conditions, without too much repetion of code


I have three cases say: Case1, Case2, Case3:

I have to define three classes depending on which case is true. All the classes have almost the same methods except for some pre-processing depending on the case. How to do it without repeating the same code over and over again?

match condition:

case: "Case1"

    class class1:
        

        def method(self):
            do something to self
            return self

case: "Case2"
    class Class2:
        

        def method(self):
            preprocessing1 on self
            do exact something as in case 1
            return self

case: "Case3"

        class Class2:
        

            def method(self):
                preprocessing2 on self
                do exact something as in case 1
                return self


How to achieve this without repeating all the code over and over again?


Solution

  • I would use inheritance, only disadvantage is definition of class1 in all cases

    Note: I don't see advantage of returning self, when you already have a reference to it

    Pseudo code mapped on your as your example is

    class class1:
        
        def method(self):
            do something to self
            
    
    case "Case2":
        class Class2(Class1):
        
            def method(self):
                preprocessing1 on self
                super().method() # do exact something as in case 1
                
    
    case "Case3":
        class Class2(Class1):
        
            def method(self):
                preprocessing2 on self
                super().method() # do exact something as in case 1