参数和子类化

Ren*_*der 0 python inheritance arguments subclassing

考虑一个矩形和一个正方形.如果我们将它们视为对象,很明显,正方形可以从矩形继承其大部分或全部属性,因为正方形是矩形的特殊情况.唯一的限制是正方形必须具有相似的边长.

看看这个非常基本的实现.

class Rectangle(object):

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def get_area(self):
        return self.x * self.y


class Square(Rectangle):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.x != self.y:
            raise ValueError("x and y must be equal.")
Run Code Online (Sandbox Code Playgroud)

为简单起见,避免了类型检查.我使用args并且kwargs为了确保子类将是未来证明.但是,我不确定我是否正确行事.Rectangleclass' __init__可能会在将来添加更多参数.

问题是,如果x和y必须相等,为什么要首先要求它们?难道不应该只有一个吗?当前的继承方案有这个限制 - 用户被迫输入x和y.怎样才能解决这个问题.将x和y转换为关键字参数不是解决方案,因为不允许使用默认值(或None).

Bre*_*arn 7

你可以这样做:

class Square(Rectangle):

    def __init__(self, x):
        super().__init__(x, x)
        if self.x != self.y:
            raise ValueError("x and y must be equal.")
Run Code Online (Sandbox Code Playgroud)

如果你想添加*args,**kwargs你可以.然而,顺便说一句,这不会做任何事情"面向未来",如果你经过*args**kwargsRectangle的,因为Rectangle不接受他们.