假设我们有一个AverageNumber类,在添加时会找到要添加的数字的平均值:
class AverageNumber():
def __init__(self, value):
self.value = value
def __add__(self, other):
average = ( self.value + other.value ) / 2 # This is the issue?
return AverageNumber(average)
def __str__(self):
return self.value
此代码是错误的,因为它没有遵守我所寻找的加法交换性和关联性,即:
平均值(1 + 3 + 2)=平均值(1 + 2 + 3)等
但是这不会发生,因为上面的类一次添加了两个。 错误结果如下:
>>> b = AverageNumber(1) + AverageNumber(3) + AverageNumber(2)
>>> b.value
2.0
>>> b = AverageNumber(1) + AverageNumber(2) + AverageNumber(3)
>>> b.value
2.25
我的问题是:如何修改上面的代码以解决此问题?
答案 0 :(得分:1)
您只需要跟踪所涉及的数字:
class AverageNumber():
def __init__(self, value, count=1):
self.value = value
self.count = count
def __add__(self, other):
total = self.value + other.value
count = self.count + other.count
return AverageNumber(total, count)
def getValue(self):
return self.value / self.count
b = AverageNumber(1) + AverageNumber(3) + AverageNumber(2)
print(b.getValue())
b = AverageNumber(1) + AverageNumber(2) + AverageNumber(3)
print(b.getValue())
Output:
2.0
2.0