当前位置: 首页 > 网络知识

Python基础入门学习笔记 038 类和对象:继承

时间:2026-01-29 09:25:52

继承

子类 父类

classDerivedClassName(BaseClassName):

……

实例:一个子类可以继承它的父类的所有属性和方法

1 >>> class Parent: 2 def hello(self): 3 print('正在调用父类的方法。。。') 4 5 6 7 >>> class Child(Parent): #子类继承父类 8 pass #直接往下执行 9 10 >>> p = Parent() 11 >>> p.hello() 12 正在调用父类的方法。。。 13 >>> c = Child() 14 >>> c.hello() 15 正在调用父类的方法。。。

如果子类中定义与父类同名的方法或属性,则会自动覆盖父类对应的方法和属性(即子类方法属性改变,父类是不变的)

1 >>> class Child(Parent): 2 def hello(self): 3 print('正在调用子类的方法') 4 5 6 >>> c = Child() 7 >>> c.hello() 8 正在调用子类的方法 9 >>> p.hello() 10 正在调用父类的方法。。。

实例2:

1 import rand as r 2 class Fish: 3 def __init__(self): 4 self.x = r.randint(0,10) 5 self.y = r.randint(0,10) 6 7 def move(self): 8 self.x = 1 9 print('我的位置是:',self.x,self.y) 10 11 12 class Goldfish(Fish): 13 pass 14 15 class Garp(Fish): 16 pass 17 18 class Shark(Fish): 19 def __init__(self): 20 self.hungry = True 21 22 def eat(self): 23 if self.hungry: 24 print('吃货的梦想就是天天有的吃') 25 self.hungry = False 26 else: 27 print('太撑了,吃不下了!') 28 29 >>> fish = Fish() 30 >>> fish.move() 31 我的位置是: 1 10 32 >>> fish.move() 33 我的位置是: 2 10 34 >>> goldfish = Goldfish() 35 >>> goldfish.move() 36 我的位置是: 2 3 37 >>> goldfish.move() 38 我的位置是: 1 3 39 >>> shark = Shark() 40 >>> shark.eat() 41 吃货的梦想就是天天有的吃 42 >>> shark.eat() 43 太撑了,吃不下了! 44 >>> shark.move() #报错原因时因为子类重写构造函数,覆盖了父类D的构造函数 45 Traceback (most recent call last): 46 File "<pyshell#9>", line 1, in <module> 47 shark.move() 48 File "D:\python3.3.2\小甲鱼python\python程序\第三十八节课\fish.py", line 8, in move 49 self.x = 1 50 AttributeError: 'Shark' object has no attribute 'x'

注:继承父类属性的子类,其变量值只属于当前子类,是子类的局部变量

报错修改部分解决方法一:调用未绑定的父类方法

>>> shark = Shark()
>>> shark.move()
我的位置是: 2 1
>>> shark.move()
我的位置是: 1 1

报错修改部分解决方法二:使用super函数(super函数会帮我们自动找到基类的方法,而且还自动为我们传入self参数)

>>> shark = Shark()
>>> shark.move()
我的位置是: 1 1
>>> shark.move()
我的位置是: 0 1

多重继承

class DerivedClassName(Base1, Base2, Base3):

……

实例:子类c同时继承基类Base1和基类Base2

1 >>> class Base1: 2 def fool1(self): 3 print('我是fool1,我为Base1代言。。。') 4 5 6 >>> class Base2: 7 def fool2(self): 8 print('我是fool2,我为Base2代言。。。') 9 10 11 >>> class C(Base1,Base2): 12 pass 13 14 >>> c = C() 15 >>> c.fool1() 16 我是fool1,我为Base1代言。。。 17 >>> c.fool2() 18 我是fool2,我为Base2代言。。。



上一篇:Python基础入门学习笔记 046 魔法方法:描述符(Property的原理)
下一篇:Python基础入门学习笔记 055 论一只爬虫的自我修养3:隐藏
python
  • 英特尔与 Vertiv 合作开发液冷 AI 处理器
  • 英特尔第五代 Xeon CPU 来了:详细信息和行业反应
  • 由于云计算放缓引发扩张担忧,甲骨文股价暴跌
  • Web开发状况报告详细介绍可组合架构的优点
  • 如何使用 PowerShell 的 Get-Date Cmdlet 创建时间戳
  • 美光在数据中心需求增长后给出了强有力的预测
  • 2027服务器市场价值将接近1960亿美元
  • 生成式人工智能的下一步是什么?
  • 分享在外部存储上安装Ubuntu的5种方法技巧
  • 全球数据中心发展的关键考虑因素
  • 英特尔与 Vertiv 合作开发液冷 AI 处理器

    英特尔第五代 Xeon CPU 来了:详细信息和行业反应

    由于云计算放缓引发扩张担忧,甲骨文股价暴跌

    Web开发状况报告详细介绍可组合架构的优点

    如何使用 PowerShell 的 Get-Date Cmdlet 创建时间戳

    美光在数据中心需求增长后给出了强有力的预测

    2027服务器市场价值将接近1960亿美元

    生成式人工智能的下一步是什么?

    分享在外部存储上安装Ubuntu的5种方法技巧

    全球数据中心发展的关键考虑因素