我应该如何实现区域和点的公共基础 class,我应该怎么称呼它?
How should I implement, and what should I call, a common base class for Area and Point?
所以我想要一个 Point
和一个 Area
class 类似于 C# 的 Point
和 Size
。下面是两个 classes 的简单实现:
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!
如您所见,两个 class 是完全相同的,除了一个 x, y
而另一个 width, height
.
为这两者实施某种基础 class 的好的解决方案是什么?
如果您不介意使用不可变对象,您可以子class tuple
为所有二维内容创建基础 class:
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])
现在,当您子 class 您的 _2dTuple
时,您只需为 x, y
和 width, height
创建 property
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]
所以我想要一个 Point
和一个 Area
class 类似于 C# 的 Point
和 Size
。下面是两个 classes 的简单实现:
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!
如您所见,两个 class 是完全相同的,除了一个 x, y
而另一个 width, height
.
为这两者实施某种基础 class 的好的解决方案是什么?
如果您不介意使用不可变对象,您可以子class tuple
为所有二维内容创建基础 class:
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])
现在,当您子 class 您的 _2dTuple
时,您只需为 x, y
和 width, height
创建 property
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]