Using __mul__

Peter Otten __peter__ at web.de
Sat Jul 3 17:28:52 CEST 2004


Sam Jervis wrote:

> Thomas Philips wrote:
>> To compute the product of a list of numbers, I tried entering
>> 
>>>>>reduce(__mul__,[1,2,3])

[...]

> The answer is in your question.  __mul__ is a valid method of type int,
> but __mul__ on its own is an undefined name.  The following code works:
> 
> reduce(int.__mul__, [1, 2, 3])

Or use operator.mul if you cannot guarantee that all numbers are integers:

>>> reduce(int.__mul__, [1.0, 2, 3])
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: descriptor '__mul__' requires a 'int' object but received a
'float'
>>> reduce(operator.mul, [1.0, 2, 3])
6.0

Peter




More information about the Python-list mailing list