面向对象之派生

【一】什么是派生

  • 派生是指子类继承父类,子类多出来自己的属性和方法,并且重用父类的属性和方法

【二】派生的方法

  • 子类可以派生出自己的新属性,在进行属性查找时,子类的属性名会优先于父类被查找
class Human:
    location = 'earth'

    def __init__(self, country, name):
        self.country = country
        self.name = name


class Chinese(Human):

    def __init__(self,country,name,language):
        self.country = country
        self.name = name
        self.language = language

    def speak(self):
        print(f'{self.name}{self.language}')


people_1 = Chinese(name='green',country='中国',language='中文')
people_1.speak()

  • 很明显子类Chinese里面的__init__方法里面的前两行都是重复代码
  • 若想在子类派生出的方法内重用父类的功能,有两种实现方法

【1】指名道姓的调用某一个类的函数#

class Human:
    location = 'earth'

    def __init__(self, country, name):
        self.country = country
        self.name = name


class Chinese(Human):

    def __init__(self,country,name,language):
        Human.__init__(self, country, name)
        self.language = language

    def speak(self):
        print(f'{self.name}{self.language}')


people_1 = Chinese(name='green',country='中国',language='中文')
people_1.speak()

【2】超类(super())#

  • 调用super()会得到一个特殊的对象
  • 该对象专门用来引用父类的属性
  • 且严格按照MRO规定的顺序向后查找
class Human:
    location = 'earth'

    def __init__(self, country, name):
        self.country = country
        self.name = name


class Chinese(Human):

    def __init__(self, country, name, language):
        super().__init__(country, name)
        self.language = language

    def speak(self):
        print(f'{self.name}{self.language}')


people_1 = Chinese(name='green', country='中国', language='中文')
people_1.speak()
  • 当使用super()函数时,Python会在MRO列表上继续搜索下一个类

【3】小结#

  • 这两种方式的区别是:
    • 方式一是跟继承没有关系的,而方式二的super()是依赖于继承的
    • 并且即使没有直接继承关系,super()仍然会按照MRO继续往后查找

作者:Esofar

出处:https://www.cnblogs.com/Hqqqq/p/17963199

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

posted @   HuangQiaoqi  阅读(22)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
more_horiz
keyboard_arrow_up dark_mode palette
选择主题
menu
点击右上角即可分享
微信分享提示