【Python进阶篇 面向对象程序设计(3) 继承】

文章目录

在面向对象编程中,被继承的类称为父类,新的类称为子类。

1、继承的基本语法

(1)单继承

bash 复制代码
# 继承
# 父类
class Fruit:
    color = '绿色'

    def harvest(self, color):
        print("水果是:" + color + "的!")
        print("水果原来是:" + Fruit.color + "的!")


# 子类
class Apple(Fruit):
    color = '红色'

    def __init__(self):
        print("我是苹果")


class Orange(Fruit):
    color = '橙色'

    def __init__(self):
        print("\n我是橘子")


apple = Apple()
apple.harvest(apple.color)
orange = Orange()
orange.harvest(orange.color)

(2)多重继承

bash 复制代码
    class 父类1:
    pass

class 父类2:
    pass

class 子类(父类1, 父类2):  # 子类继承多个父类
    pass 

2、方法重写

子类可以覆盖父类的方法,实现自定义行为。

bash 复制代码
class Animal:
    def speak(self):
        return "通用叫声"

class Dog(Animal):
    def speak(self):  # 重写父类方法
        return "Woof!"

3、super()函数

调用父类的方法(常用于初始化和扩展功能)。

bash 复制代码
class Fruit:
    def __init__(self, color="绿色"):
        Fruit.color = color

    def harvest(self):
        print("水果原来是:" + Fruit.color + "的!")


class Apple(Fruit):
    def __init__(self):
        print("我是苹果!")


apple = Apple()
apple.harvest()

直接运行上面的代码有报错:

原因是在子类的__init__()方法中不会自动调用父类的__init__()方法,需要使用super()函数。

bash 复制代码
class Fruit:
    def __init__(self, color="绿色"):
        Fruit.color = color

    def harvest(self):
        print("水果原来是:" + Fruit.color + "的!")


class Apple(Fruit):
    def __init__(self):
        print("我是苹果!")
        super().__init__()  ## 调用父类的__init__()方法


apple = Apple()
apple.harvest()
相关推荐
刀法如飞5 分钟前
一款开箱即用的Flask 3.0 MVC工程脚手架,面向AI开发
后端·python·flask
xingpanvip9 分钟前
星盘接口开发文档:组合三限盘接口指南
android·开发语言·前端·python·php·lua
DeeGLMath14 分钟前
使用optimtool训练符号神经网络
人工智能·深度学习·神经网络
无忧.芙桃23 分钟前
现代C++讲解之变量模板,泛型lambda,函数返回类型推导的使用
开发语言·c++·visualstudio
码农的神经元23 分钟前
拆解 SDGT 算法:图神经网络 + Transformer 如何做短期电力负荷预测
神经网络·算法·transformer
格林威1 小时前
工业视觉检测:两大主流异常检测开源框架深度对比(PatchCore vs SPADE)
开发语言·人工智能·深度学习·数码相机·计算机视觉·视觉检测·工业相机
2zcode1 小时前
基于Matlab元胞自动机模拟(CA)静态再结晶过程
开发语言·matlab·静态再结晶
vortex51 小时前
Villain:新一代轻量级 C2 框架完整使用指南
python·网络安全·kali·c2
测试员周周1 小时前
【AI测试系统】第5篇:AI 编码工具抛硬币?我们用 LangGraph 做了个“确定性+AI”的测试系统(附自愈架构)
人工智能·python·功能测试·测试工具·架构·langchain·单元测试
研究点啥好呢1 小时前
滴滴Go后端开发工程师面试题精选:10道高频考题+答案解析
java·开发语言·golang