主頁 > 知識(shí)庫 > Python的運(yùn)算符重載詳解

Python的運(yùn)算符重載詳解

熱門標(biāo)簽:客戶服務(wù) 電話運(yùn)營中心 語音系統(tǒng) Win7旗艦版 硅谷的囚徒呼叫中心 呼叫中心市場需求 企業(yè)做大做強(qiáng) 百度AI接口

一、前言

運(yùn)算符重載:為運(yùn)算符定義方法

所謂重載,就是賦予新的含義同一個(gè)運(yùn)算符可以有不同的功能

二、重載作用

讓自定義的實(shí)例像內(nèi)建對(duì)象一樣進(jìn)行運(yùn)算符操作讓程序簡介易讀對(duì)自定義對(duì)象將運(yùn)算符賦予新的規(guī)則 運(yùn)算符和特殊方法 運(yùn)算符重載

# @function:運(yùn)算符重載
# @Description: 一只螢火蟲

class MyInteger:
    """
    創(chuàng)建一個(gè)自定義的整數(shù)類型
    """
    def __init__(self, data=0):
        # 1.如果傳入的參數(shù)時(shí)是整數(shù)類型,那么直接賦值
        # 2.如果傳入的不是整數(shù)類型,則判斷能夠轉(zhuǎn)化成整數(shù),不能轉(zhuǎn)換就賦初值為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):
            # 返回當(dāng)前對(duì)象的副本
            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(對(duì)象)時(shí)被自動(dòng)調(diào)用
        :return: 用來返回對(duì)象的可讀字符串形式(適合普通用戶閱讀)
        """
        return str(self.data)

    def __repr__(self):
        """ 用來將對(duì)象轉(zhuǎn)換成供解釋器讀取的形式,用來閱讀對(duì)象的底層繼承關(guān)系及內(nèi)存地址"""
        return "[自定義整數(shù)類型的值]:{}\t地址:{}".format(self.data, id(self.data))

    def __sub__(self, other):
        return MyInteger(self.data - other.data)

    def __del__(self):
        print("當(dāng)前對(duì)象:" + str(self.data) + "被銷毀")     # 程序運(yùn)行完之后自動(dòng)被銷毀


if __name__ == '__main__':
    num1 = MyInteger(123)
    num2 = MyInteger(321)
    num3 = num1 + num2      # 等價(jià)于:num3 = num1.__add__(num2)
    print("num3 =", num3)
    num4 = MyInteger("123")
    num5 = num4 + 124       # 在自定義對(duì)象的右側(cè)相加整數(shù)類型
    num6 = 124 + num4       # 在自定義對(duì)象的左側(cè)相加整數(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):
        # 讓本類的對(duì)象支持下標(biāo)訪問
        if isinstance(index, int):
            return self.data[index]
        elif type(index) is slice:      # 如果參數(shù)是切片類型 [10:30:2]
            print("切片的起始值:", index.start)
            print("切片的結(jié)束值:", 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):
        # 默認(rèn)刪除并返回最后一個(gè)元素
        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("刪除并返回最后一個(gè)元素:", my_list1.pop())
    del my_list1[1]
    print("刪除指定下標(biāo)的元素:", my_list1)
	
輸出結(jié)果:
顯示列表: [0, 1111, 2, 3, 4, 5, 6, 7, 8, 9]
切片的起始值: 2
切片的結(jié)束值: 8
切片的步長: 8
列表的切片: [2, 4, 6]
刪除并返回最后一個(gè)元素: 9
刪除指定下標(biāo)的元素: [0, 2, 3, 4, 5, 6, 7, 8]

到此這篇關(guān)于Python的運(yùn)算符重載詳解的文章就介紹到這了,更多相關(guān)Python運(yùn)算符重載內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:
  • Python運(yùn)算符重載詳解及實(shí)例代碼
  • Python運(yùn)算符重載用法實(shí)例分析
  • Python運(yùn)算符重載用法實(shí)例
  • Python 捕獲代碼中所有異常的方法
  • Python同時(shí)處理多個(gè)異常的方法
  • 解決python ThreadPoolExecutor 線程池中的異常捕獲問題
  • 使用Python將Exception異常錯(cuò)誤堆棧信息寫入日志文件
  • 解決Python 異常TypeError: cannot concatenate ''str'' and ''int'' objects
  • Python 輸出詳細(xì)的異常信息(traceback)方式
  • 解析python高級(jí)異常和運(yùn)算符重載

標(biāo)簽:長沙 濟(jì)南 山西 海南 安康 喀什 崇左 山西

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Python的運(yùn)算符重載詳解》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266