zoukankan      html  css  js  c++  java
  • 运算符的重载【掌握】

    overload

    重载:两个类,如果在 一个类中重新实现了一个方法

    对专有的方法进行重载

    代码演示:

    #+普通用法
    #数字和数字相加:数学运算
    print(24 + 49)
    #字符串和字符串相加:拼接
    print("fdh" + "ghaur")
    
    #print("ahfg" + 16)  #ypeError: must be str, not int
    #不同的数据类型的加法操作会有不同的解释
    
    class Person(object):
        def __init__(self,num):
            self.num = num
    
        def __str__(self):
            return "num = " + str(self.num)
    
        #运算符重载
        #在程序中,但凡涉及到+运算,在底层都会调用__add__,
        def __add__(self, other):
            return Person(self.num + other.num)
    
    p1 = Person(23)
    p2 = Person(12)
    
    
    print(p1,p2)
    
    #int+int = int   str+str = str   person+person = person
    p3 = p1 + p2
    print(p3)
    print(p3.__str__())   #35
    print(p1.__add__(p2))   #p1 + p2 =====>p1.__add__(p2)
    
    """
    def text(str1,num1):
        return  str1 + str(num1)
    
    text("abc" + 18)
    """
    
    #使用场景:当系统的某些功能满足不了需求时,就可以在类中进行重载,函数的实现体部分完全可以自定义
  • 相关阅读:
    决策树和随机森林
    6个开源数据科学项目
    机器学习:梯度下降
    Python中的数据结构
    方差分析介绍(结合COVID-19案例)
    html5
    归并排序
    前端与后端
    Dw3 Sublime text 3 UltraEdit XAMMPP 火狐浏览器 ISS
    ECMAScript JavaScript JScript
  • 原文地址:https://www.cnblogs.com/allwell/p/10004095.html
Copyright © 2011-2022 走看看