python使用add进行重载加法

2025-12-01 0 66,501

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

1、先定义一个类:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
 
>>> a = Point(2, 4)
>>> b = Point(3, 5)
>>> a + b
Traceback (most recent call last):
  File "/usr/local/python3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2862, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "", line 1, in 
    a + b
TypeError: unsupported operand type(s) for +: 'Point' and 'Point'

很显然 a 和 b 并不能相加,但是我们可以定义一个方法让它们实现相加。

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    # 定义一个 add 方法
    def add(self, other):
        return Point(self.x + other.x, self.y + other.y)
 
>>> a = Point(2, 4)
>>> b = Point(3, 5)
>>> c = a.add(b)
>>> c.x
Out[6]: 5

2、通过一个 add 方法,我们实现了它们的相加功能。但是,我们还是习惯使用加号,事实上,我们只要改下函数名就可以使用 + 进行运算了。

   def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)

很显然 + 就是调用类的 __add__ 方法,因为我们只要加入这个方法就能够实现加法操作。

以上就是python使用add进行重载加法,希望能对大家有所帮助。更多Python学习指路:python基础教程

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:以上部本文内容由互联网用户自发贡献,本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。投诉邮箱:3758217903@qq.com

ZhiUp资源网 python基础 python使用add进行重载加法 https://www.zhiup.top/2229.html

相关