Home > Enterprise >  How to not overwrite a method from parent class because of a simple change in the code (in Python)
How to not overwrite a method from parent class because of a simple change in the code (in Python)

Time:01-11

I have something like this:

def Class1:
    ...
    
    def __getitem__(self, index):
        ...a lot of code
        a = query["label_1"].iat[index]
        ...some more operations
        return a

def Class2(Class1):
    ...
    
    def __getitem__(self, index):
        ...a lot of code which is the same as Class1
        a = query["label_2"].iat[index]
        ...some more operations which are identical in Class1
        return a
    

As you can see, both "__getitem__" functions are basically the same, but only changes "label_1" to "label_2". There is a way to not to overwrite the entire method in Class2 just because of a little change?

CodePudding user response:

You could use a class variable called label:

class Class1:

  label = "label_1"

  def __getitem__(self, index):
    a = query[self.label].iat[index]
    return a

class Class2(Class1):

    label = "label_2"

And you do not have to overwrite __getitem__ in Class2, just having defined the class variable in Class2 will work.

  • Related