Python的運算符重載詳解
更新時間:2021年05月12日 10:05:01 作者:一只螢火蟲
這篇文章主要介紹了Python的運算符重載詳解,文中有非常詳細的代碼示例,對正在學習python的小伙伴們有非常好的幫助,需要的朋友可以參考下
一、前言
運算符重載:為運算符定義方法
所謂重載,就是賦予新的含義同一個運算符可以有不同的功能
二、重載作用
讓自定義的實例像內建對象一樣進行運算符操作讓程序簡介易讀對自定義對象將運算符賦予新的規(guī)則 運算符和特殊方法 運算符重載
# @function:運算符重載 # @Description: 一只螢火蟲 class MyInteger: """ 創(chuàng)建一個自定義的整數(shù)類型 """ def __init__(self, data=0): # 1.如果傳入的參數(shù)時是整數(shù)類型,那么直接賦值 # 2.如果傳入的不是整數(shù)類型,則判斷能夠轉化成整數(shù),不能轉換就賦初值為0 if isinstance(data, int): self.data = data elif isinstance(data, str) and data.isdecimal(): self.data = int(data) else: self.data = 0 def __add__(self, other): if isinstance(other, MyInteger): # 返回當前對象的副本 return MyInteger(self.data + other.data) # 相加的是MyInteger類型 elif isinstance(other, int): return MyInteger(self.data + other) # 相加的是整型 def __radd__(self, other): return self.__add__(other) def __eq__(self, other): if isinstance(other, MyInteger): return self.data == other.data elif isinstance(other, int): return self.data == other else: return False def __str__(self): """ 在打印、str(對象)時被自動調用 :return: 用來返回對象的可讀字符串形式(適合普通用戶閱讀) """ return str(self.data) def __repr__(self): """ 用來將對象轉換成供解釋器讀取的形式,用來閱讀對象的底層繼承關系及內存地址""" return "[自定義整數(shù)類型的值]:{}\t地址:{}".format(self.data, id(self.data)) def __sub__(self, other): return MyInteger(self.data - other.data) def __del__(self): print("當前對象:" + str(self.data) + "被銷毀") # 程序運行完之后自動被銷毀 if __name__ == '__main__': num1 = MyInteger(123) num2 = MyInteger(321) num3 = num1 + num2 # 等價于:num3 = num1.__add__(num2) print("num3 =", num3) num4 = MyInteger("123") num5 = num4 + 124 # 在自定義對象的右側相加整數(shù)類型 num6 = 124 + num4 # 在自定義對象的左側相加整數(shù)類型 print("num5 = ", num5, "\t num6 = ", num6) num7 = MyInteger(1024) num8 = MyInteger(1024) print("num7 == num8 :", num7 == num8)
三、自定義列表
# @function:自定義列表 # @Description:一只螢火蟲 class MyList: def __init__(self, data=None): self.data = None if data is None: self.data = [] else: self.data = data def __getitem__(self, index): # 讓本類的對象支持下標訪問 if isinstance(index, int): return self.data[index] elif type(index) is slice: # 如果參數(shù)是切片類型 [10:30:2] print("切片的起始值:", index.start) print("切片的結束值:", index.stop) print("切片的步長:", index.stop) return self.data[index] def __setitem__(self, key, value): self.data[key] = value def __contains__(self, item): print("判斷傳入的", item, "是否在列表元素中") return self.data.__contains__(item) def __str__(self): return str(self.data) def pop(self, index=-1): # 默認刪除并返回最后一個元素 return self.data.pop(index) def __delitem__(self, key): del self.data[key] def append(self, item): self.data.append(item) if __name__ == '__main__': my_list1 = MyList([item for item in range(10)]) my_list1[1] = 1111 print("顯示列表:", my_list1) print("列表的切片:", my_list1[2:8:2]) print("刪除并返回最后一個元素:", my_list1.pop()) del my_list1[1] print("刪除指定下標的元素:", my_list1) 輸出結果: 顯示列表: [0, 1111, 2, 3, 4, 5, 6, 7, 8, 9] 切片的起始值: 2 切片的結束值: 8 切片的步長: 8 列表的切片: [2, 4, 6] 刪除并返回最后一個元素: 9 刪除指定下標的元素: [0, 2, 3, 4, 5, 6, 7, 8]
到此這篇關于Python的運算符重載詳解的文章就介紹到這了,更多相關Python運算符重載內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
python實現(xiàn)word 2007文檔轉換為pdf文件
這篇文章主要為大家詳細介紹了python實現(xiàn)word 2007文檔轉換為pdf文件,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-03-03Python?數(shù)據(jù)分析教程探索性數(shù)據(jù)分析
這篇文章主要介紹了Python?數(shù)據(jù)分析教程探索性數(shù)據(jù)分析,文章圍繞主題展開詳細的內容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-08-08Python?Asyncio?庫之同步原語常用函數(shù)詳解
這篇文章主要為大家介紹了Python?Asyncio?庫之同步原語常用函數(shù)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-03-03python numpy矩陣信息說明,shape,size,dtype
這篇文章主要介紹了python numpy矩陣信息說明,shape,size,dtype,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05