Let's say I have a class TT inheriting from a class T and extending the behaviour of one of its methods, like so:
class T:
def __init__(self, p, b):
self.p = p
self.b = b
self.fun()
def fun(self):
a = self.p + self.b
print(a)
class TT(T):
def __init__(self, p, b):
super().__init__(p, b)
def fun(self):
super().fun()
c = self.p*self.b
print(c)
What I'd like to have is TT.fun relying on variables defined in T.fun, a in this example. The two obvious things that came to mind are to make T.fun return a, or to make a an instance variable, but I don't find either satisfactory. Is there a way for TT.fun to share the scope of the method it extends?
EDIT
Thanks for the answers.
To expand on my use case, my derived classes run some sort of optimisation of a vector against a dataset. The parent class is here to suggest a common, coherent interface to the different optimisations.
In a class' function to be optimised, some steps (depending on the current state of the vector) are shared by all the subclasses, which is why I figured I'd put it in a parent method. And as Lagerbaer suggests, they were already run in the equivalent of a "private" compute_a() method; what I had in mind was to call this method to bring the results to scope in the parent class, so I wouldn't have to do it in individual subclasses. Turns out, given the small number of subclasses I'm dealing with, duplicating a few lines of code may be the simplest thing to do here.
As to Nathaniel Ford's suggestions, this is why I don't find my initial solutions to be satisfactory:
- I don't need this value once the optimisation has been run, and it changes at every optimisation step, that's why I don't think it makes sense to save it as an instance variable.
- Returning the value would lead to the extended method behaving differently as its parent (in a signature sense).
- I don't want anything lingering in a global scope.
As you pointed out, my thinking was not encapsulation-friendly; such a reminder is good to have occasionally!