【问题标题】:how to overload the + operator for point class on python? [duplicate]如何在python上重载点类的+运算符? [复制]
【发布时间】:2014-01-10 03:23:48
【问题描述】:

如何重载点类的 + 运算符,使其与点对象或元组一起使用。

如果第二个操作数是一个点,该方法应该返回一个新的点,其 x 坐标是 操作数的 x 坐标之和,y 坐标也是如此。

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

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

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

       self.x = x
       self.y = y

我仍在研究它,而且我是 python 新手,所以任何类型的想法都会有很大帮助。

【问题讨论】:

  • (a) 你可以让 Point 扩展元组,然后只使用索引。 (b) numpy 对向量有很好的支持,如果你开始在你的点上使用矩阵变换,这将有所帮助。 (c) 我通常会使用一个复数(例如1 + 2j)作为二维点,尽管这取决于应用程序。
  • 不相关的问题,但 Point 继承自 objectclass Point(object): 并为自己省去一些可能的麻烦。

标签: python python-2.7 tuples overloading


【解决方案1】:

定义__add__。如果要允许tuple + Point,还要定义__radd__

>>> 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

【讨论】:

  • 这没有回答如何让__add__ 处理点元组...
  • @MartinStettner,我更新了答案。感谢您的评论。
【解决方案2】:

只需覆盖 __add__ 魔术方法:

def __add__(self, other):
    if isinstance(other, tuple):
         x, y = other #tuple unpacking
         return Point(self.x+x, self.y+y)
    elif isinstance(other, Point):
         x, y = other.x, other.y #Just for consistency
         return Point(self.x+x, self.y+y)
    else:
         raise TypeError("That data type is not supported")

这是一个小演示:)

>>> p = Point(10, 20) + Point(1, 2)
>>> p.x
11
>>> p.y
22
>>> p = Point(10, 20) + "asfbde"
Traceback (most recent call last):
  File "<pyshell#169>", line 1, in <module>
    p = Point(10, 20) + "asfbde"
  File "<pyshell#165>", line 14, in __add__
    raise TypeError("That data type is not supported")
TypeError: That data type is not supported

希望这会有所帮助!

【讨论】:

    【解决方案3】:

    你可以试试

     class Point:
        # ...
        def __add__(self, other):
            if type(other) is tuple:
                return Point(self.x+other[0], self.y + other[1])
            else:
                return Point(self.x+other.x, self.y+other.y)
    

    【讨论】:

    • 对于身份比较,请使用is 运算符。
    • 谢谢,好点。改了。
    猜你喜欢
    • 2010-10-21
    • 1970-01-01
    • 2017-01-29
    • 2013-03-07
    • 2018-06-01
    • 2014-10-11
    • 2012-03-14
    • 1970-01-01
    • 2010-12-28
    相关资源
    最近更新 更多