所以我想要一个类似于C#Point
和Area
的{{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
。
为这两个实现某种基类有什么好的解决方案?
答案 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
时,您只需为property
和x, 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]