添加一个既支持点对象又支持元组的方法

0 投票
2 回答
1892 浏览
提问于 2025-04-17 03:51

我的一个练习题要求我为点(Point)写一个 add 方法,这个方法可以处理点对象或者元组(tuple):

  • 如果第二个操作数是一个点对象,这个方法应该返回一个新的点,这个点的 x 坐标是两个操作数的 x 坐标之和,y 坐标也是同样的道理。
  • 如果第二个操作数是一个元组,这个方法应该把元组的第一个元素加到 x 坐标上,把第二个元素加到 y 坐标上,然后返回一个新的点,包含这个结果。

这是我目前写的代码,但我不确定元组那部分的代码是否正确。有人能帮我解释一下怎么调用这个程序来处理元组部分吗?我觉得我第一部分写得不错。

这是我的代码:

Class Point():
    def__add__(self,other):
            if isinstance(other,Point):
                    return self.add_point(other)
            else:
                    return self.print_point(other)

    def add_point(self,other):
            totalx = self.x + other.x
            totaly = self.y + other.y
            total = ('%d, %d') % (totalx, totaly)
            return total

    def print_point(self):
            print ('%d, %d) % (self.x, self.y)

    blank = Point()
    blank.x = 3
    blank.y = 5
    blank1 = Point()
    blank1.x = 5
    blank1.y = 6

这就是我目前的进展,但我不太确定怎么用元组那部分来运行这个代码。我知道如果执行 blank + blank1,if 部分会运行并调用 add_point 函数,但我该怎么初始化元组呢?我不确定我写得对不对……请帮帮我。

2 个回答

2

你可以简单地让你的类继承自元组(或者只需要实现一下 __getitem__ 方法)。

class Point(tuple):
    def __new__(cls, x, y):
        return tuple.__new__(cls, (x, y))

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

    def __repr__(self):
        return 'Point({0}, {1})'.format(self[0], self[1])

p = Point(1, 1)
print p + Point(5, 5) # Point(6, 6)
print p + (5, 5)      # Point(6, 6)
1

另外,如果你想使用 point.x 和 point.y 这样的写法,你可以实现以下代码:

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

    def __add__(self, other): 
        if isinstance(other, Point):
            return Point(self.x + other.x, self.y + other.y)
        elif isinstance(other, tuple):
            return Point(self.x + other[0], self.y + other[1])
        else:
            raise TypeError("unsupported operand type(s) for +: 'Point' and '{0}'".format(type(other)))

    def __repr__(self):
        return u'Point ({0}, {1})'.format(self.x, self.y) #Remove the u if you're using Python 3

撰写回答