Is __mul__ sufficient for operator '*'?
Muhammad Alkarouri
malkarouri at gmail.com
Mon Oct 19 20:31:44 EDT 2009
Hi everyone,
I was having a go at a simple implementation of Maybe in Python when I
stumbled on a case where x.__mul__(y) is defined while x*y is not.
The class defining x is:
class Maybe(object):
def __init__(self, obj):
self.o = obj
def __repr__(self):
return 'Maybe(%s)' % object.__getattribute__(self, "o")
def __getattribute__(self, name):
try:
o = object.__getattribute__(self, "o")
r = getattr(o,name)
if callable(r):
f = lambda *x:Maybe(r(*x))
return f
else:
return Maybe(r)
except:
return Maybe(None)
The code exercising this class is:
>>> x=Maybe(9)
>>> x.__mul__(7)
Maybe(63)
>>> x*7
Traceback (most recent call last):
File "<pyshell#83>", line 1, in <module>
x*7
TypeError: unsupported operand type(s) for *: 'Maybe' and 'int'
The farthest I can go in this is that I presume that __mul__ (as
called by operator *) is supposed to be a bound method while I am
returning a lambda function. Is this correct? And How can I make the
implementation support such operators?
Cheers,
Muhammad Alkarouri
More information about the Python-list
mailing list