我正在尝试创建具有坐标属性的Class,该属性可以为多维情况计算两个对象之间的距离和减法。
class CoordN():
def __init__(self, *args):
self.coords = args
self.dimentions = len(args)
def __check(self, other):
if not isinstance(other, CoordN):
raise ValueError('Not the same type')
else:
if self.dimentions != other.dimentions:
raise ValueError('Not the same dimentions')
def distance(self, other):
self.__check(other)
self.deltas = ()
for i in range(self.dimentions):
self.deltas += ((self.coords[i] - other.coords[i])**2,)
return (sum(self.deltas))**0.5
def __sub__(self, other):
self.__check(other)
self.substraction = ()
for i in range(self.dimentions):
self.substraction += (self.coords[i] - other.coords[i],)
return eval ('CoordN' + str(self.substraction))
# return CoordN(self.substraction)
当我定义__sub__
方法时,我使用了eval
语句,因为如果我使用return CoordN(self.substraction)
,它将返回元组中的元组。
>>> c1 = CoordN(0,0,0)
>>> c2 = CoordN(2,2,2)
>>> d = c2 - c1
>>> d.coords
((2, 2, 2),)
是否可以避免使用eval
?