‘‘‘ in her it 继承 de rive 派生 python2 (经典类|新式类) python3 (新式类) 1. What is inheritance? 什么是继承? 继承是一种新建类的方式 新建的类为 --> 子类or派生类 父类称为 --> 基类or超类 python中支持多继承 2. Why inheritance? 为什么用继承? 减少代码的冗(rong)余 减少代码的啰嗦··· 3. How to use inheritance? 怎么用继承? 通过内置__bases__查找继承类 4. 寻找继承关系: --> 继承是类与类之间的关系,寻找这种关系需要先抽象再继承 5. 查找名称空间: 自类 --> 父类 --> 爷(父类的父类)类 ‘‘‘ # -- ( inherit: Ex--> ) ------------------------------------------------------------------------------------------- # class Dad: # pass # class Mom: # pass # class Son(Dad, Mom): # pass # print(Son.__bases__) # # (<class ‘__main__.Dad‘>, <class ‘__main__.Mom‘>) # -- ( 继承:抽象继承 ) ------------------------------------------------------------------------------------------- # -- ( 找出一样的属性,抽出 ) ------------------------------------------------------------------------------------------- ‘‘‘ class Dad: # 定义父类 family = ‘Happiness‘ def __init__(self, name, age, sex): self.name = name self.age = age self.sex = sex class Son(Dad): # 继承(父类) def son_son(self): print(‘儿子%s‘%self.name) class Kid(Dad): # 继承(父类) def kid_kid(self): print(‘小子%s‘%self.name) # 实例化对象(传参) Max = Kid(‘Max‘,24,‘male‘) Oscer = Kid(‘Oscer‘,4,‘male‘) # 验证结果 print(Oscer.name,Oscer.age,Oscer.sex)# Enter --> Oscer 4 male print(Max.name,Max.age,Max.sex)# Enter --> Max 24 male print(Max.kid_kid()) # Enter --> 小子Max print(Max.family) # Enter --> Happiness PS: 实例化类中,一定优先查找自身的名称空间,然后查找父类 即使在父类有函数输出调用,也是从自身类开始运行输出 ‘‘‘ # -- ( 抽象继承,找出一样的属性,抽出 ) -------------------------------------------------------------------------------------------
原文地址:https://www.cnblogs.com/max404/p/10743733.html
时间: 2024-09-30 19:48:43