在__init__中使用继承的类方法 [英] Use inherited class method within __init__

查看:122
本文介绍了在__init__中使用继承的类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由几个孩子继承的父类。我想使用父级的 @classmethod 初始值设定项初始化其中一个孩子。我怎样才能做到这一点?我试过了:

I have a parent class that is inherited by several children. I would like to initialize one of the children using the parent's @classmethod initializers. How can I do this? I tried:

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 __ ,那么 PointOnUnitCircle 具有与 Point 不同的接口(因为它需要 angle 而不是 x,y )因此不应该是它的子类。如下所示:

If you try to write __init__ like that, your PointOnUnitCircle has a different interface to Point (as it takes angle rather than x, y) and therefore shouldn't really be a sub-class of it. How about something like:

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)

这使接口成为sam e,添加逻辑以检查子类的输入(一旦你编写它!)并提供一个新的类方法,从<$ c轻松构造一个新的 PointOnUnitCircle $ C>角度。而不是

This keeps the interface the same, adds logic for checking the inputs to the subclass (once you've written it!) and provides a new class method to easily construct a new PointOnUnitCircle from an angle. Rather than

p3 = PointOnUnitCircle(pi/4)

你必须写

p3 = PointOnUnitCircle.from_angle(pi/4)

这篇关于在__init__中使用继承的类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆