I am developing an object oriented application which is very similar to the following limited working example. I am initiating 2 super classes. Class A
and class B
. Class A
defines variables var1
and var2
, and contains methods Add
, Multiply
, Power
. Class B
defines variables var1
and var2
and contains methods Subtract
, Divide
and Add
.
Class C
instantiates an instance of both class A
and class B
. It then defines a method f1
which utilizes methods from A_obj
and B_obj
with different names. Notice that method f2
is using the method Add
from A_obj
and B_obj
. The method has the same name but performs a different computation.
The last few lines of the code instantiate an object of class C
and then prints out the results using both functions.
class A():
def __init__(self, var1, var2):
self.var1 = var1
self.var2 = var2
def Add(self):
result = self.var1 + self.var2
return result
def Multiply(self):
result = self.var1*self.var2
return result
def Power(self):
result = self.var1**self.var2
class B():
def __init__(self, var1, var2):
self.var1 = var1
self.var2 = var2
def Subtract(self):
result = self.var1-self.var2
return result
def Divide(self):
result = self.var1/self.var2
return result
def Add(self):
result = self.var1+self.var2+self.var1+self.var2
return result
class C():
def __init__(self, var1, var2, var3, var4):
self.A_obj = A(var1,var2)
self.B_obj = B(var3,var4)
def f1(self):
result = self.A_obj.Add()+self.B_obj.Subtract()
return result
def f2(self):
result = self.A_obj.Add()-self.B_obj.Add()
return result
C_obj = C(1, 2, 3,4)
print(C_obj.f1())
print(C_obj.f2())
My question is, can I achieve this sort of functionality using inheritance? Is inheritance even an appropriate concept to use here? I tried forcing it in a previous question but found out that as soon as you use inheritance variables in subclass C
become "globally defined" and are recognized by superclasses A
and B
. I'd like to make sure everything in class A
remains local to A
and everything in class B
remain local to B
.