Using __mul__

T

Thomas Philips

To compute the product of a list of numbers, I tried entering

Traceback (most recent call last):
File "<pyshell#0>", line 1, in -toplevel-
reduce(__mul__,[1,2,3])
NameError: name '__mul__' is not defined

I can get the answer I want by defining a function that returns the
product of two numbers: return x*y

and then using it:
6

But why does my first approach not work? __mul__ is a valid method of
type int. Is there an obvious flaw in my logic?

Thomas Philips
 
S

Sam Jervis

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


Traceback (most recent call last):
File "<pyshell#0>", line 1, in -toplevel-
reduce(__mul__,[1,2,3])
NameError: name '__mul__' is not defined

I can get the answer I want by defining a function that returns the
product of two numbers:

return x*y

and then using it:
reduce(product,[1,2,3])

6

But why does my first approach not work? __mul__ is a valid method of
type int. Is there an obvious flaw in my logic?

Thomas Philips

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])

Sam
 
P

Peter Otten

Sam said:
Thomas said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top