• Python笔记_第三篇_面向对象_3.重载(overloading)和重写(overriding)


    1. 重载

      overloading:就是将函数重新定义一遍。

      1.1 __str__( )和__repr__( )的重载:

      格式:

      __str__( ):在调用print打印对象时自动调用,是给用户用的,是一个描述对象的方法。

      __repr__( ):给机器用的,在Python解释器或者在cmd的黑屏终端里面输入,注意在没有str时,且有repr,str = repr,其实本事就是打印类本身想要实现的属性。

      举例说明1:

    class Person(object):
        def __init__(self,name,age,height,weight):  
            self.name = name
            self.age = age
            self.height = height
            self.weight = weight
        def __str__(self):
            # return "这里是__str__"
            return "%s-%d-%d-%d" %(self.name,self.age,self.height,self.weight)
        # def __repr__(self):
        #     # return "这里是__str__"
        #     return "%s-%d-%d-%d" %(self.name,self.age,self.height,self.weight)
    
    
    per = Person("hanmeimei",20,170,55)
    print(per)
    print(per.__str__())  # 其实不写入类体重,这里也是可以直接打印的。
    # hanmeimei-20-170-55
    # hanmeimei-20-170-55

      优点:当一个对象的属性值很多的时候,兵器都需要打印,重写__str__方法后,简化了代码。  

       

      1.2 __add__( ) 的重载

      比如我们有这么两个运算

      print(1 + 2)

      print("1" + "2")

      我们知道,返回的结果一个是3,一个是12。前面是一个int类型的数值,后面是一个字符串。也就是说,不同类型的加法会有不同给的解释。

      因此我们在类中重新定义一个加法的重载。

      格式:

      __add__(self,other):sef代表加号前面的对象,other表示加法后面的对象。  

      举例说明2:

    class Person(object):
        def __init__(self,num):
            self.num = num
        # 运算符重载
        def __add__(self, other):  #self 代表加号前面的对象,other表示加法后面的对象
            return Person(self.num + other.num)
        def __str__(self):
            return "num = " + str(self.num)
    
    per1 = Person(1)
    per2 = Person(2)
    print(per1 + per2)
    print(per1.__add__(per2))
    # num = 3

      1.3 其他重载

      Python当中的重载也不算很多,我下面列举了一个小表格,对Python的重载进行罗列

      在很多教材中:重载也叫Python的魔法方法。

      

      小贴士:

       help和dir

      help可以查询相关的内容解释,dir可以查看目录内的内容。

    help("__add__()")
    # 用help去查找帮助内容:
    # No Python documentation found for '__add__()'.
    # Use help() to get the interactive help utility.
    # Use help(str) for help on the str class.
    
        
    class Person(object):
        def __init__(self,name):
            self.name = name
    
    per = Person("Tom")
    print(dir(per))
    # 现实类相关的内容
    # ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', 
    #  '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', 
    #  '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', 
    #  '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', 
    #  '__str__', '__subclasshook__', '__weakref__', 'name']

    2. 重写

      overriding:就是一个类当中可以有一个以上的方法具有相同名称。

      举例说明1:

    class Person(object):
        def __init__(self,name,age,height,weight):
            self.name = name
            self.age = age
            self.height = height
            self.weight = weight
    
        def run(self):
            print("run1")
    
        def run(self):
            print("run2")
    
    per = Person("hanmeimei",20,170,55)
    per.run()
    # 返回值:run2

      其实我们发现Python并不需要重载。在C#语言中,重载时两个相同的函数名,且参数类型不一样,类似于:

      run(int b)

      run(long b)

      这种函数时重载的现象。但是python里面的重载其实就是识别最后一个函数的意思。

       

      举例说明2:我们在通过一个类的继承来观察重写,在父类中有一个run方法,子类继承父类,也有一个相同的run方法。我们发现也是最后面那个重写的run2进行加载

    class Person(object):
        def __init__(self,name,age,height,weight):
            self.name = name
            self.age = age
            self.height = height
            self.weight = weight
    
        def run(self):
            print("run1")
    
    class Worker(Person):
        def __init__(self,name,age,height,weight):
            super(Worker,self).__init__(name,age,height,weight)
    
        def run(self):
            print("run2")
    
    per = Person("hanmeimei",20,170,55)
    wor = Worker("Tom",20,170,60)
    wor.run()
    # 返回值:run2
  • 相关阅读:
    DockerFile构建步骤及命令
    linux安装nginx及常用命令
    docker常用命令
    Docker安装
    获取TrustedInstaller权限
    获取本机公网ip的url地址
    centOS7配置ip
    VS Code配置c语言环境
    Linux l 2.4.20-8 # 溢出
    VMware Destination Host Unreachable
  • 原文地址:https://www.cnblogs.com/noah0532/p/10858370.html
Copyright © 2020-2023  润新知