class inheritance

Jean-Michel Pichavant jeanmichel at
Mon Mar 15 19:24:38 CET 2010

JLundell wrote:
> I've got a subclass of fractions.Fraction called Value; it's a mostly
> trivial class, except that it overrides __eq__ to mean 'nearly equal'.
> However, since Fraction's operations result in a Fraction, not a
> Value, I end up with stuff like this:
> x = Value(1) + Value(2)
> where x is now a Fraction, not a Value, and x == y uses
> Fraction.__eq__ rather than Value.__eq__.
> This appears to be standard Python behavior (int does the same thing).
> I've worked around it by overriding __add__, etc, with functions that
> invoke Fraction but coerce the result. But that's tedious; there are a
> lot of methods to override.
> So I'm wondering: is there a more efficient way to accomplish what I'm
> after?
I would change the approach.
To the question, "*is* a Value a Fraction", some may tempted to answer 
"No" (for instance, a fraction has a denominator, a value has not).
However "Does a Fraction *have* a Value", you could possibly say "Yes".

The value may be then an attribute of the class Fraction, not a subclass.
To test fraction equality, use F1 == F2. In order to test 'nearly 
equality', use F1.val() == F2.val().


More information about the Python-list mailing list