I have two classes with a common function f
, like here:
class ClassA(object):
def f(self, var):
self.A = g(var, self.A)
# specific code for ClassA, also changing self.A
class ClassB(object):
def f(self, var):
self.B = g(var, self.B)
# specific code for ClassB, also changing self.B
In both classes, f
does the same on two variables called A
and B
, which are structurally equivalent. I would like to put f
it into an abstract class to avoid code duplication. One way to do this is
class ClassX(object):
def f(self, var):
self.X = g(var, self.X)
class ClassA(ClassX):
# specific code for ClassA, also changing self.X
class ClassB(ClassX):
# specific code for ClassB, also changing self.X
In this solution the variables A
and B
have been renamed X
. However, to make my code more self-explaining, I would like to keep those specific names (say A
,B
) for X
in the special classes.
Is there a way to do this?
Also please comment if you can suggest a more meaningful and descriptive title, so it becomes more valuable to the community.
Edit: The solution should also work if the variables A
, B
take a type which is pass-by-value and should assume that both their value and type might be changed from outside the class during the program execution.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…