新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:python使用add進行重載加法
本文教程操作環(huán)境:windows7系統(tǒng)、python 3.9.1,DELL G3電腦。

創(chuàng)新互聯(lián)是少有的網(wǎng)站設計制作、成都網(wǎng)站設計、營銷型企業(yè)網(wǎng)站、成都小程序開發(fā)、手機APP,開發(fā)、制作、設計、外鏈、推廣優(yōu)化一站式服務網(wǎng)絡公司,于2013年創(chuàng)立,堅持透明化,價格低,無套路經(jīng)營理念。讓網(wǎng)頁驚喜每一位訪客多年來深受用戶好評
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 并不能相加,但是我們可以定義一個方法讓它們實現(xiàn)相加。
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 方法,我們實現(xiàn)了它們的相加功能。但是,我們還是習慣使用加號,事實上,我們只要改下函數(shù)名就可以使用 + 進行運算了。
def __add__(self, other): return Point(self.x + other.x, self.y + other.y)
很顯然 + 就是調(diào)用類的 __add__ 方法,因為我們只要加入這個方法就能夠?qū)崿F(xiàn)加法操作。
以上就是python使用add進行重載加法,希望能對大家有所幫助。更多Python學習指路:創(chuàng)新互聯(lián)Python教程
網(wǎng)站欄目:創(chuàng)新互聯(lián)Python教程:python使用add進行重載加法
轉(zhuǎn)載源于:http://www.fisionsoft.com.cn/article/dhgpgji.html


咨詢
建站咨詢
