2017-12-02 71 views
-2

我想我的对象Foo的方法返回平均总和。对于只有两个对象的总和起来很简单:使__add__返回算术平均值

class Foo(): 
    def __init__(self, n): 
     self.n = n 

    def __add__(self, other): 
     return Foo((self.n + other.n)/2) 

如何为N>2对象做到这一点?例如。 Foo(0) + Foo(1) + Foo(2) + Foo(3)应返回Foo((0 + 1 + 2 + 3)/4),即Foo(1.5)

========================================

编辑:这是我的解决方案

class Foo():  
    def __init__(self, n): 
     self.n = n 
     self._n = n 
     self._count = 1 

    def __add__(self, other): 
     out = Foo(self._n + other._n) 
     out._count = self._count + other._count 
     out.n = out.n/out._count 
     return out 

无法得到算术平均值的最佳方式,但我需要做这种方式。此外,这还演示了如何执行用户定义对象的特殊添加,该对象返回对象总和的函数。例如。使__add__返回的对象的总和的平方根:

class Bar(): 
    def __init__(self, n): 
     self.n = n 
     self._n = n 

    def __add__(self, other): 
     out = Bar(self._n + other._n) 
     out.n = (out.n)**0.5 
     return out 
+2

这听起来像一个非常糟糕的主意。除了这是不可能的事实,它会使你的代码非常令人沮丧。 –

+0

不需要任何解释就可以降低投票率......这让你不知道问题或我发布的代码有什么问题。没有人从中受益。有一个明确的任务必须以这种特殊的方式完成,尽管它看起来像一个“坏主意”。正如我所展示的,可以通过几行易于理解的代码来完成。 – Andyk

+0

请将您的答案作为实际答案发布,而不是作为问题中的修改。 –

回答

2

一种解决方案可以在类中的两个数字来存储:平均值和样本数量:

class Foo: 
    def __init__(self, avg, count=1): 
     self.avg = avg 
     self.count = count 

    def __add__(self, other): 
     return Foo((self.avg*self.count + other.avg*other.count) 
             /
          (self.count + other.count), 
        self.count + other.count) 

更妙的是仅存储总和并仅在请求时计算平均值。