Question Details

No question body available.

Tags

python subclassing

Answers (2)

March 8, 2026 Score: 3 Rep: 369,277 Quality: Medium Completeness: 80%

Is this the intended behaviour?

Yes, because the implementation of the methods in Lib/fractions.py explicitly return instances of Fraction instead of instances of type(self) (example source for addition).

Is there a way around?

There is, but not from the subclass. The way around would have to be done in Fraction itself, to allow for the possibility of operations on subtypes to return instances of subtypes. This would be done by making the methods return type(self)(...) instead of explicitly returning Fraction. An example of a built-in type which does work like that is datetime:

>>> from datetime import datetime, timedelta >>> class D(datetime): ... pass ... >>> D(2026, 3, 7) D(2026, 3, 7, 0, 0) >>> D(2026, 3, 7) + timedelta(1) # still a D instance, even though add wasn't overridden D(2026, 3, 8, 0, 0)
March 8, 2026 Score: 1 Rep: 3,202 Quality: Low Completeness: 40%

You could just not subclass it. Monkey-patching a wrapper will be clunky no matter what you do; you might be better served by using functions with Fraction parameters instead of subclass methods. This has the added benefit of not forcing you to convert Fraction instances to subclass instances every time you call those functions.