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

38 Views Asked by At

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?

2

There are 2 best solutions below

5
alhernau On BEST ANSWER

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
            
0
alhernau On

Trying to help, but I know I'll learn more than I can teach, factorizing class definition after comment from SIGHUP.

class Class1:

    def __init__(self,case="Case1"):
        self.content = "Raw"

    def method(self):
        self.content = f"Class1 method applied to ({self.content})"
        print(self.content)
        return self
    

class Class2(Class1):

    def __init__(self,case="Case2"):
        super().__init__()
        self.case = case

    def _preprocessing_1(self):
        self.content = f"_preprocessing_1 applied to ({self.content})"
        print(self.content)
        return self

    def _preprocessing_2(self):
        self.content = f"_preprocessing_2 applied to ({self.content})"
        print(self.content)
        return self
    
    def method(self):
        if self.case == "Case2":
            self._preprocessing_1()
        else:
            self._preprocessing_2()     
        super().method() # do exact something as in case 1
        return self
    
    
print("Case1")
c1 = Class1()
c1.method()

print("Case2")
c2 = Class2()
c2.method()

print("Case3")
c3 = Class2("Case3")
c3.method()