2014-10-22 46 views
1

我有期望,reduce(add,lst)sum(lst)应该给我相同的结果名单上,但`减少(增加,...)``VS总和(...)`,为什么第二次失败的对象

In [18]: class p(): 
    def __init__(self, x, y): 
     self.x=x ; self.y=y 
    def __repr__(self): 
     return "(%r,%r)"%(self.x,self.y) 
    def __add__(self, P): 
     return p(self.x+P.x, self.y+P.y) 
    ....:  
In [19]: pts=[p(1,0), p(2,1), p(-3,4)] 
In [20]: from operator import add 
In [21]: print reduce(add,pts) 
(0,5) 
In [22]: print sum(pts) 
--------------------------------------------------------------------------- 
TypeError         Traceback (most recent call last) 
<ipython-input-22-98a81789d257> in <module>() 
----> 1 print sum(pts) 
TypeError: unsupported operand type(s) for +: 'int' and 'instance' 
In [23]: 

当然我不理解的东西,可能很明显;有人能教导我吗?

回答

10

reduce()pts[0]作为初始值(除非您给出明确的起始值),但sum()默认为0。从sum() function documentation

sum(iterable[, start])
的款项开始和可迭代的由左到右,并返回总的项目。 开始默认为0

give sum() a better start value;使用的第一个对象,就像reduce()作用:

sum(pts[1:], pts[0]) 

或合适的空值:

sum(pts, p(0, 0)) 
0

如果定义__radd__特殊情况下,如果0被添加到您的对象的实例,那么你就可以只需使用sum()即可。

... rest of Point class defn ... 
def __radd__(self, other): 
    if other == 0: 
     return self 
    raise TypeError("invalid type to add to point") 

print sum(pts) 

会给(0,5)