You can override the subclass's __new__
method to construct instances from the superclass's alternate constructor as shown below.
import math
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
@classmethod
def from_polar(cls, radius, angle):
x = radius * math.cos(angle)
y = radius * math.sin(angle)
return cls(x, y)
class PointOnUnitCircle(Point):
def __new__(cls, angle):
point = Point.from_polar(1, angle)
point.__class__ = cls
return point
def __init__(self, angle):
pass
Note that in __new__
, the line point = Point.from_polar(1, angle)
cannot be replaced by point = super().from_polar(1, angle)
because whereas Point
sends itself as the first argument of the alternate constructor, super()
sends the subclass PointOnUnitCircle
to the alternate constructor, which circularly calls the subclass's __new__
that calls it, and so on until a RecursionError
occurs. Also note that even though __init__
is empty in the subclass, without overriding __init__
in the subclass, the superclass's __init__
would automatically be called immediately after __new__
, undoing the alternate constructor.
Alternatively, some object designs are simpler with composition than with inheritance. For example, you could replace the above PointOnUnitCircle
class without overriding __new__
with the following class.
class UnitCircle:
def __init__(self, angle):
self.set_point(angle)
def set_point(self, angle):
self.point = Point.from_polar(1, angle)