如何在python上为点类重载+运算符?

use*_*845 1 python overloading tuples python-2.7

如何为点类重载+运算符,使其适用于点对象或元组.

如果第二个操作数是Point,则该方法应该返回一个新的Point,其x坐标是操作数的x坐标的总和,同样也是y坐标的总和.

如果第二个操作数是元组,则该方法应将元组的第一个元素添加到x坐标,将第二个元素添加到y坐标,并返回带有结果的新Point.

到目前为止,我得到的只是点类,它是:

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

       self.x = x
       self.y = y
Run Code Online (Sandbox Code Playgroud)

我仍在努力,我是python的新手,所以任何类型的想法都将是一个很大的帮助.

fal*_*tru 5

定义__add__.还要定义__radd__是否允许tuple + Point.

>>> 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])
...         raise TypeError
...     def __radd__(self, other):
...         return self + other
...
>>> p = Point(1, 2) + Point(3, 4)
>>> p.x
4
>>> p.y
6
>>> p2 = Point(1, 2) + (1, 1)
>>> p2.x
2
>>> p2.y
3
>>> p3 = (4, 0) + Point(1, 3)
>>> p3.x
5
>>> p3.y
3
>>> Point(1, 3) + 'x'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 10, in __add__
TypeError
Run Code Online (Sandbox Code Playgroud)