On Tue, 17 Feb 2009 09:48:30 +0100, Luca Bacchi <bacch...@gmail.com> wrote: > Esiste un protocollo per l'operatore 'sum'?
No, cosa fare è spiegato nella sua documentazione (forse sono le implicazioni a non essere chiare): sum(sequence, start=0) -> value Returns the sum of a sequence of numbers (NOT strings) plus the value of parameter 'start'. When the sequence is empty, returns start. c'è un parametro start, che vale 0. sum non inizia sommando i primi due elementi della lista, ma sommando start col primo elemento della lista. > Questo è quello che vorrei, più o meno: > > class A(object): > def __init__(self, v): > self.v = v > > > sum([A(1), A(2), A(3)]) > > dove il risultato dovrebbe essere 6, ossia la somma delle varie proprietà > 'v'. Basta fornire uno "start" sensibile: In [8]: class A(object): def __init__(self, v): self.v = v def __add__(self, other): return A(self.v + other.v) ....: ....: In [14]: sum([A(1), A(2), A(3)], A(0)).v Out[14]: 6 Alternativamente, puoi definire __add__ in maniera che supporti la somma A + int, nel qual caso va bene anche lo "start" di default. Un altro esempio: puoi usare sum per concatenare una lista di liste, ma devi usare una lista vuota come "start": In [16]: LL = [ range(i) for i in range(5) ] In [17]: LL Out[17]: [[], [0], [0, 1], [0, 1, 2], [0, 1, 2, 3]] In [18]: sum(LL, []) Out[18]: [0, 0, 1, 0, 1, 2, 0, 1, 2, 3] Ciao! -- Daniele Varrazzo - Develer S.r.l. http://www.develer.com _______________________________________________ Python mailing list Python@lists.python.it http://lists.python.it/mailman/listinfo/python