Ziva
Ziva

Reputation: 3511

Python - inheritance and method overriding

I have two classes, one inheriting from the other. Let's call them Parent and Child. Both of the objects created from those classes should use function funA, which looks like below

funA():
  X = another_function()
  Y = # some value
  X.append(Y)
  # do other computations

For both classes, function funA looks almost the same, except function another_function(), which computes in a different way the list X for the Parent and differently for the Child. Of course, I know that I can override function funA in the Child class, but since this function is very long and does several operations, copy-pasting it would be a little bit a waste. On the other hand - I have to distinguish that the Parent class should use one version of another_function() and the Child class should use the second version of another_function(). Is is maybe possible to point which version of another_function (let's call them another_function_v1 and another_function_v2) should be used by each class or the only solution if to override the whole function funA?

Upvotes: 0

Views: 1627

Answers (2)

milo
milo

Reputation: 1917

I don't know where your another_functions come. I suppose they are normal functions, which can be imported and used

class Parent(object):
    another_function = another_function_v1
    def funA(self):
        X = self.another_function()
        Y = # some value
        X.append(Y)
        # do other computations

class Child(Parent):
    another_function = another_function_v2

Upvotes: 1

bruno desthuilliers
bruno desthuilliers

Reputation: 77942

Your post is not quite clear but I assume funA is a method of Parent. If yes, just add some another_method method calling the right function:

class Parent(object):
    def another_method(self):
        return another_function_v1()

    def funA(self):
        X = self.another_method()
        Y = # some value
        X.append(Y)
        # do other computations

class Child(Parent):
    def another_method(self):
        return another_method_v2()

nb if funA is a classmethod you will want to make another_method a classmethod too...

Upvotes: 1

Related Questions