【一】什么是派生
- 派生是指子类继承父类,子类多出来自己的属性和方法,并且重用父类的属性和方法
【二】派生的方法
- 子类可以派生出自己的新属性,在进行属性查找时,子类的属性名会优先于父类被查找
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继续往后查找
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!