Loading

面向对象之派生

【一】什么是派生

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

【二】派生的方法

  • 子类可以派生出自己的新属性,在进行属性查找时,子类的属性名会优先于父类被查找
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继续往后查找
posted @ 2024-01-13 23:19  HuangQiaoqi  阅读(10)  评论(0编辑  收藏  举报