如果你尝试写__init__
像这样,你的PointOnUnitCircle
有不同的接口Point
(因为它需要angle
而不是x, y
)因此不应该真正成为它的子类。怎么样:
class PointOnUnitCircle(Point):
def __init__(self, x, y):
if not self._on_unit_circle(x, y):
raise ValueError('({}, {}) not on unit circle'.format(x, y))
super(PointOnUnitCircle, self).__init__(x, y)
@staticmethod
def _on_unit_circle(x, y):
"""Whether the point x, y lies on the unit circle."""
raise NotImplementedError
@classmethod
def from_angle(cls, angle):
return cls.from_mag_angle(1, angle)
@classmethod
def from_mag_angle(cls, mag, angle):
# note that switching these parameters would allow a default mag=1
if mag != 1:
raise ValueError('magnitude must be 1 for unit circle')
return super(PointOnUnitCircle, cls).from_mag_angle(1, angle)
这使接口保持不变,添加了用于检查子类输入的逻辑(一旦您编写了它!)并提供了一个新的类方法来轻松构造新的PointOnUnitCircle
从一个angle
。而不是
p3 = PointOnUnitCircle(pi/4)
你必须写
p3 = PointOnUnitCircle.from_angle(pi/4)