In Python (2.7), I want to create a class of rational numbers that mimics the behavior of the Fraction class (in modular fractions), but overrides the __repr__ method to match the result of __str__. The original idea was only for my own messing around, and just to make the IDLE result look more friendly. But now I'm more interested in understanding the basic inheritance / typing problem, which, in my opinion, may be of general interest, as opposed to getting a workaround for this particular use case, which is admittedly trivial.
The problem is that I would like to inherit the functionality of all numeric operators (__add__, __sub__ methods, etc.), but there are results as instances of my subclass, not fractions. This is what I want, but instead it happens:
class Q(Fraction):
def __repr__(self):
return str(self)
>>> Q(1,2)
1/2
>>> Q(1,2) + Q(1,3)
Fraction(5, 6)
This is because the operators defined in Fraction return instances of Fraction. Of course, I could redefine all these magic methods individually, calling the parent class to do the math, and then forcing my type, but I believe there should be a way to deal with this repetitive situation as a whole (i.e. without spelling "def" 20 times).
__getattribute__ , , , , . ( , __getattr__ , , , , !)
, , , ?