I a newbie in Python OOP and I have a problem with the below program. When I run it, it gives me an error AttributeError: 'MyClass' object has no attribute 'sum'. This problem can be fix easily by replace the line sum = self.sum at each function compute_sqrtSum(), compute_SumSquare() and compute_SumCube() by sum = self.compute_Sum(). But if so, every time the program run these three functions, it has to run compute_Sum() once, in total three times. So is there a way that I can access to sum but only run compute_Sum() once?
class MyClass:
def __init__(self, x, y):
self.x = x
self.y = y
def compute_Sum(self):
sum = self.x + self.y
self.sum = sum
return sum
def compute_sqrtSum(self):
sum = self.sum
sqrt_sum = sqrt(sum)
return sqrt_sum
def compute_SumSquare(self):
sum = self.sum
sum_sq = sum * sum
return sum_sq
def compute_SumCube(self):
sum = self.sum
sum_cb = sum * sum * sum
return sum_cb
user = MyClass(1, 2)
print(user.compute_sqrtSum())
print(user.compute_SumSquare())
print(user.compute_sqrtCube())
compute_Sum()before or inside the other methods.compute_Sum()more than once?self.sum = self.x + self.ydirectly in__init__and you will no need to usecompute_Sum()__init__setself.sum = Noneand in other functions runscompute_Sum()only whenself.sum is None