how to extend the method of a class in a child class without returning all its variables

Viewed 31

Let's say I have a base class:

class B: 

    def __init__(self):
        self.b = 3
        return 

    def method(self,x):
        y  = 2 * self.b
        x *= 2
        y *= (x + 2)
        return x

It does some manipulations based on self.b and produces a variable y that is not returned by method. Say, I have now a class A which derives from B and will look very similar, but it shall extend the functionality of B's method() by doing additional operations:

class A(B) 

    def __init__(self):
        super().__init__()
        return 

    def extended_method(self,x):

        x = self.method(x)

        if y<=10: 
            y = 10 

        return x,y

    def what_As_extended_method_should_do(self,x):

        y  = 2 * self.b
        x *= 2
        y *= (x + 2)

        if y<=10: 
            y = 10 

        return x,y

extended_method shows the way I'd like to write it, but this will cause an undefined variable error. The method what_As_extended_method_should_do shows what the method should do. But instead of having to write the same code inside B.method() several times (say I have 10 different subclasses which all slightly change B.method(), I would like to have some wrapper that automatically takes B.method()'s y into its scope and can operate on it without undefined variable error. The crux is that I cannot simply return x AND y from B.method(), just x. Does anybody know a solution?

Thanks!

0 Answers
Related