On Mar 13, 1:26 pm, Carl Banks <pavlovevide...@gmail.com> wrote: > It's a tad unfortunately Python doesn't make this easier. If I had to > do it more than once I'd probably write a mixin to do it: > > class ArithmeticSelfCastMixin(object): > def __add__(self,other): > return > self.__class__(super(ArithmeticSelfCastMixin,self).__add__(other) > # etc. > > class Value(ArithmeticSelfCastMixin,fraction.Fraction): > pass > > However, I want to warn you about overriding __eq__ to mean "almost > equal": it can have unexpected results so I don't recommend it. Two > of the main issues with it are: > > 1. It violates the transitive property ("If A == B and B == C, then A > == C") which most programmers expect to be true. > > 2. It will give unpredictable results when the objects are used in > sets or as dictionary keys. Those thow types expect the transitive > property to be true. If you are going to redefine __eq__ to mean > "almost equal", then at least define __hash__ to raise > NotImplementedError so that Python will refuse to use them in sets or > as dictionary keys: > > def __hash__(self): raise NotImplementedError > > Carl Banks
It's also unfortunate that Python doesn't have an approximately-equal operator; it'd come in handy for floating-point applications while preserving hash. If only there were a ~= or ≈ operator I could overload. And ~ is unary, so no joy. My application is in that sense a little like a floating-point app, in that it needs approximately-equal. And it doesn't need Value to be hashable; thanks for the NotImplementedError suggestion; I've done that as a safeguard. -- http://mail.python.org/mailman/listinfo/python-list