我应该如何实现,以及我应该称之为Area和Point的公共基类?

时间:2016-03-31 06:26:05

标签: python python-3.x subclass base-class

所以我想要一个类似于C#PointArea的{​​{1}}和Point类。以下是两个类的简单实现:

Size

正如您所看到的,这两个类是完全相同的,除了一个有class Point: def __init__(self, x=0, y=0): self.x = x self.y = y def __add__(self, other): return Point(self.x + other.x, self.y + other.y) # Many other magic methods too! class Area: def __init__(self, width=0, height=0): self.width = width self.height = height def __add__(self, other): return Area(self.width + other.width, self.height + other.height) # Many other magic methods too! 而另一个有x, y

为这两个实现某种基类有什么好的解决方案?

1 个答案:

答案 0 :(得分:1)

如果您不介意使用不可变对象,可以将tuple子类化为所有二维内容的基类:

class _2dTuple(tuple):

     def __new__(cls, hor=0, ver=0):
         super().__new__(cls, (hor, ver))

     def __add__(self, other):
         return type(self)(self[0] + other[0], self[1] + other[1])

现在,当您继承_2dTuple时,您只需为propertyx, y创建width, height个getter:

class Point(_2dTuple):

    @property
    def x(self):
        return self[0]

    @property
    def y(self):
        return self[1]


class Area(_2dTuple):

    @property
    def width(self):
        return self[0]

    @property
    def height(self):
        return self[1]
相关问题