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

标签 python inheritance class-method

我有一个由多个子类继承的父类。我想使用父项的 @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/

相关文章:

python - 在 Python 中展平任意嵌套列表的最快方法是什么?

python - 使 arctan2() 连续超过 2pi

python - 如何在 Django 模板中从 Matplotlib 输出图形?

python - 获取异常 : AttributeError __aenter__

sql - Rails 3 中继承的命名范围映射到错误的表

c++ - 从基类构造函数构造派生类对象

python - 如何从同一个类的类方法调用实例方法

c# - 面向对象 : Using Properties and Constructor

python - 在创建 Python 类时调用类方法

Objective-C:使用静态变量