App下載

Python的運算符重載詳解

愛嘯的女孩超愛看你笑 2021-08-19 11:06:24 瀏覽數(shù) (5573)
反饋

運算符重載是一種賦予運算符新的功能的方法。在python中也可以進行運算符的重載。接下來就讓我們來看看python怎么進行運算符重載吧。

一、前言

運算符重載:為運算符定義方法

所謂重載,就是賦予新的含義同一個運算符可以有不同的功能

二、重載作用

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

在這里插入圖片描述

# @function:運算符重載
# @Description: 一只螢火蟲

class MyInteger:
    """
    創(chuàng)建一個自定義的整數(shù)類型
    """
    def __init__(self, data=0):
        # 1.如果傳入的參數(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):
            # 返回當前對象的副本
            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(對象)時被自動調(diào)用
        :return: 用來返回對象的可讀字符串形式(適合普通用戶閱讀)
        """
        return str(self.data)

    def __repr__(self):
        """ 用來將對象轉(zhuǎn)換成供解釋器讀取的形式,用來閱讀對象的底層繼承關(guān)系及內(nèi)存地址"""
        return "[自定義整數(shù)類型的值]:{}	地址:{}".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       # 在自定義對象的右側(cè)相加整數(shù)類型
    num6 = 124 + num4       # 在自定義對象的左側(cè)相加整數(shù)類型
    print("num5 = ", num5, "	 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("切片的結(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):
        # 默認刪除并返回最后一個元素
        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)
	
輸出結(jié)果:
顯示列表: [0, 1111, 2, 3, 4, 5, 6, 7, 8, 9]
切片的起始值: 2
切片的結(jié)束值: 8
切片的步長: 8
列表的切片: [2, 4, 6]
刪除并返回最后一個元素: 9
刪除指定下標的元素: [0, 2, 3, 4, 5, 6, 7, 8]

到此這篇Python的運算符重載詳解就介紹到這了,更多Python學習內(nèi)容請搜索W3Cschool以前的文章或繼續(xù)瀏覽下面的相關(guān)文章。

1 人點贊