当前位置: 首页 > news >正文

12.2 类的派生

12.2 类的派生

1.类的查找顺序

#父类
class Foo:def f1(self):print('Foo.f1')def f2(self): #bprint('Foo.f2')self.f1()#子类
class Bar(Foo):def f1(self):print('Bar.f1')b = Bar()
b.f2() #查找顺序:Bar()->Foo.f2()->输出Foo.f2->bar.f1()->输出Bar.f1#输出
Foo.f2
Bar.f1
Foo.f2
Bar.f1

2. 类的派生

添加新的属性的同时还有继承父类的所有东西

#方法1:
class Animal():def __init__(self,height,weight):self.height=heightself.weight=weightdef jiao(self):print(self.__class__.__name__,'叫')
# Animal.__init__(111,185,140) #类调用传3个参数,对象调用传2个参数class People(): def __init__(self,name,age,height,weight):Animal.__init__(self,height,weight)self.name=nameself.age=agedef read(self):print('read')def sleep(self):print(f'self_sleep')peo=People('coco',18,185,140)print(peo.__dict__)
{'height': 185, 'weight': 140, 'name': 'coco', 'age': 18}

方法1总结:

  • 不需要继承也可以做到
  • 派生:继承父类属性的同时增加新的属性, 然后使用
  • 引出方法2,方法2对方法1进行封装
#方法2:(重点)
class Animal():def __init__(self,height,weight):self.height=heightself.weight=weightdef jiao(self):print(self.__class__.__name__,'叫')class People(Animal): def __init__(self,name,age,height,weight):super().__init__(height,weight) #规定的语法super会自动调用父类的__init__,并且拿到height、weightself.name=nameself.age=agedef read(self):print('read')def sleep(self):print(f'self_sleep')
peo=People('coco',18,185,140)print(peo.__dict__)
{'height': 185, 'weight': 140, 'name': 'coco', 'age': 18}

方法2总结:继承才可以

  • super().init(height,weight)

尽量只继承一个父类,遵从线性继承的规则。

#继承XingXing的gender
class Animal():def __init__(self,height,weight):self.height=heightself.weight=weightdef jiao(self):print(self.__class__.__name__,'叫')class XingXing(Animal): #继承Animaldef __init__(self,height,weight,gender):super().__init__(height,weight)self.gender=genderdef sleep(self):print('sleep')class People(XingXing): #继承XingXing def __init__(self,name,age,height,weight,gender):super().__init__(height,weight,gender) self.name=nameself.age=agedef read(self):print('read')def sleep(self):print(f'self_sleep')
peo=People('coco',18,185,140,'male')print(peo.__dict__)#线性继承:People继承XingXing,XingXing继承Animal。
{'height': 185, 'weight': 140, 'gender': 'male', 'name': 'coco', 'age': 18}

http://www.agseo.cn/news/322/

相关文章:

  • CSP-S模拟18
  • 在服务器后台运行python服务
  • HCIP回顾—2 OSPF工作过程及状态机制
  • python基础——函数小进阶
  • 你的开发服务器在说谎-热重载与热重启的关键区别
  • 在疼痛中,在喧嚣 失聪与惶惑中
  • AT_agc018_b [AGC018B] Sports Festival
  • 11.5 类与数据类型
  • 开发手记(二)——图片转换成base64编码
  • C++《C++11》(上) - 详解
  • NOIP2025专题-图论2 专题简记
  • 接口
  • 1
  • 无重复字符的最长子串的解题分析
  • ClaudeCode实现简单需求文档分析与拆分
  • python基础——数据容器(序列、集合、字典)
  • 提取符号偏移地址
  • 11.4 类与对象的绑定方法
  • 【初赛】排序 - Slayer
  • Overpass – TryHackMe
  • nvm管理node
  • 浅拷贝和深拷贝两种不同的对象复制
  • NPU前端编译器常见的优化
  • LG11755
  • 「LAOI-9」Update
  • ABC393F
  • ABC393E
  • ABC393D
  • ZR 25 noip D1T2 题解 | 最短路
  • NOIP2024 退役记