gpt4 book ai didi

python - 在 __init__ 中使用继承的类方法

转载 作者:行者123 更新时间:2023-11-30 23:04:34 25 4
gpt4 key购买 nike

我有一个由多个子类继承的父类。我想使用父项的 @classmethod 初始化其中一个子项初始化器。我怎样才能做到这一点?我尝试过:

class Point(object):
def __init__(self,x,y):
self.x = x
self.y = y

@classmethod
def from_mag_angle(cls,mag,angle):
x = mag*cos(angle)
y = mag*sin(angle)
return cls(x=x,y=y)


class PointOnUnitCircle(Point):
def __init__(self,angle):
Point.from_mag_angle(mag=1,angle=angle)


p1 = Point(1,2)
p2 = Point.from_mag_angle(2,pi/2)
p3 = PointOnUnitCircle(pi/4)
p3.x #fail

最佳答案

如果您尝试写__init__就像这样,你的PointOnUnitCirclePoint有不同的界面(因为它需要 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)

这使接口(interface)保持不变,添加了用于检查子类输入的逻辑(一旦您编写了它!),并提供了一个新的类方法来轻松构造新的 PointOnUnitCircle来自angle 。而不是

p3 = PointOnUnitCircle(pi/4)

你必须写

p3 = PointOnUnitCircle.from_angle(pi/4)

关于python - 在 __init__ 中使用继承的类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33632219/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com