当前位置: 首页 > 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.zskr.cn/news/262.html

相关文章:

  • NOIP2025专题-图论2 专题简记
  • 在疼痛中,在喧嚣 失聪与惶惑中
  • 开发手记(二)——图片转换成base64编码
  • Overpass – TryHackMe
  • 浅拷贝和深拷贝两种不同的对象复制
  • NPU前端编译器常见的优化
  • ABC393E
  • ABC393D
  • ZR 25 noip D1T2 题解 | 最短路
  • NOIP2024 退役记
  • LG11311
  • CF1746F
  • C#.NET EFCore.BulkExtensions 扩展详解
  • 2025AI赋能HR新纪元,中国AI HR主流厂商大盘点
  • 私有化部署Dify构建企业AI平台教程
  • 树状数组板子2
  • NOIP 集训日记
  • 记录---让网页像现实世界一样“拿起来,放进去”
  • Ubuntu22.04安装Docker过程记录
  • MySQL多表查询
  • 软件工程导论第一次作业
  • 闲话 25.9.8
  • The 2025 ICPC Asia East Continent Online Contest (I)
  • Ubuntu22.04下Docker的安装Docker镜像源问题解决方法
  • 【项目实战】基于Hi3861的鸿蒙智能小车(循迹、超声波避障、远程控制、语音控制、4G定位)有教程代码
  • 【项目实战】基于Hi3861的鸿蒙智能小车(循迹、超声波避障、远程控制、语音控制、4G定位)有教程代码
  • 新手小白如何快速入门PostgreSQL
  • Linux Strace 系统调用工具详解与企业应用
  • 想进大厂?从学习圈子里的“管理术语”开始
  • 配电网二进制粒子群重构(BPSO)