A similar question was asked in Initialize subclass within class in python. The answers there concluded that this kind of approach should be avoided, I am not sure if this is true for the following case, and I would like to know either how it can be achieved, or what I should do instead.
class Rational():
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
if self.denominator == 1:
pass
# >>> How to initialize as Integer in this case? <<<
# ... More methods for rationals
class Integer(Rational):
def __init__(self, value):
super().__init__(value, 1)
self.value = value
# ... More methods for integers
In this file, I have simple classes for Integer and Rational
numbers. Since all Integer
s are rational, Integer
is a subclass of rational, and we call super()
to allow methods for rational numbers to be called by the integer.
It would be nice though, if whenever a Rational
was initialized with denominator 1, it could be automatically recognized as an integer. For example, I would want x = Rational(4, 1)
to then allow me to call x.integer_method()
or even have Integer(4) == x
return True. The trouble is, I don't know if I can call the Integer
initializer from the Rational
initializer because I may be caught in an infinite loop.
What is the best way to resolve this (in a general way that works not just for integers and rationals, but for any Parent-Child type where an instance of Parent might not be recognized as semantically equivalent to a member of Child type until initialization time?