Python from Wise Guy's Viewpoint
Alex Martelli
aleax at aleax.it
Mon Oct 20 11:15:34 EDT 2003
Pascal Costanza wrote:
...
> So how do you implement an equality operator correctly with only single
> dynamic dispatch?
Equality is easy, as it's commutative -- pseudocode for it might be:
def operator==(a, b):
try: return a.__eq__(b)
except I_Have_No_Idea:
try: return b.__eq__(a)
except I_Have_No_Idea:
return False
Non-commutative operators require a tad more, e.g. Python lets each
type define both an __add__ and a __radd__ (rightwise-add):
def operator+(a, b):
try: return a.__add__(b)
except (I_Have_No_Idea, AttributeError):
try: return b.__radd__(a)
except (I_Have_No_Idea, AttributeError):
raise TypeError, "can't add %r and %r" % (type(a),type(b))
Multimethods really shine in HARDER problems, e.g., when you have
MORE than just two operands (or, perhaps, some _very_ complicated
inheritance structure -- but in such cases, even multimethods are
admittedly no panacea). Python's pow(a, b, c) is an example --
and, indeed, Python does NOT let you overload THAT (3-operand)
version, only the two-operand one that you can spell pow(a, b)
or a**b.
ALex
More information about the Python-list
mailing list