华域联盟 Python Python的运算符重载详解

Python的运算符重载详解

目录

一、前言

运算符重载:为运算符定义方法

所谓重载,就是赋予新的含义同一个运算符可以有不同的功能

二、重载作用

让自定义的实例像内建对象一样进行运算符操作让程序简介易读对自定义对象将运算符赋予新的规则 运算符和特殊方法 运算符重载

# @function:运算符重载
# @Description: 一只萤火虫

class MyInteger:
    """
    创建一个自定义的整数类型
    """
    def __init__(self, data=0):
        # 1.如果传入的参数时是整数类型,那么直接赋值
        # 2.如果传入的不是整数类型,则判断能够转化成整数,不能转换就赋初值为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 "[自定义整数类型的值]:{}\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       # 在自定义对象的右侧相加整数类型
    num6 = 124 + num4       # 在自定义对象的左侧相加整数类型
    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:      # 如果参数是切片类型 [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运算符重载内容请搜索华域联盟以前的文章或继续浏览下面的相关文章希望大家以后多多支持华域联盟!

您可能感兴趣的文章:

本文由 华域联盟 原创撰写:华域联盟 » Python的运算符重载详解

转载请保留出处和原文链接:https://www.cnhackhy.com/23145.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部