详细分析Python的继承和多态(附Demo)

前言

入行多年,对于知识点还会混淆,此处主要做一个详细区分

  • 继承(Inheritance):
    面向对象编程中的一个重要概念,允许一个类(称为子类或派生类)继承另一个类(称为父类或基类)的属性和方法,子类可以访问父类的所有非私有属性和方法,并且可以添加自己的属性和方法
  • 多态(Polymorphism):
    不同类的对象可以对相同的方法做出不同的响应,代表具有相同方法名的不同类的对象可以根据自己的实现方式来执行这个方法

1. 继承

继承的相关语法:

# 定义一个父类
class ParentClass:
    def parent_method(self):
        print("This is a parent method.")

# 定义一个子类,继承自父类
class ChildClass(ParentClass):
    def child_method(self):
        print("This is a child method.")

# 创建子类对象
child_obj = ChildClass()

# 调用子类的方法
child_obj.child_method()  # 输出:This is a child method.

# 子类可以调用父类的方法
child_obj.parent_method()  # 输出:This is a parent method.

截图如下:

在这里插入图片描述

下述逻辑如此,就不截图了

一、单继承

# 定义一个父类
class Animal:
    def make_sound(self):
        pass

# 定义子类 Dog,继承自 Animal
class Dog(Animal):
    def make_sound(self):
        return "Woof!"

# 创建 Dog 对象
dog = Dog()

# 调用子类方法
print(dog.make_sound())  # 输出:Woof!

二、多继承

# 定义一个父类
class Bird:
    def make_sound(self):
        pass

# 定义另一个父类
class Mammal:
    def make_sound(self):
        pass

# 定义一个子类,同时继承 Bird 和 Mammal
class Bat(Bird, Mammal):
    def make_sound(self):
        return "Squeak!"

# 创建 Bat 对象
bat = Bat()

# 调用子类方法
print(bat.make_sound())  # 输出:Squeak!

2. 多态

多态性通过动态类型检查和动态绑定实现。具体来说,当调用对象的方法时,Python 会根据对象的类型来确定应该调用哪个方法

以下这个Demo比较形象:

# 定义一个父类 Animal
class Animal:
    def make_sound(self):
        pass

# 定义子类 Dog,继承自 Animal
class Dog(Animal):
    def make_sound(self):
        return "Woof!"

# 定义子类 Cat,继承自 Animal
class Cat(Animal):
    def make_sound(self):
        return "Meow!"

# 函数接受 Animal 类的对象作为参数,并调用其 make_sound 方法
def make_sound(animal):
    print(animal.make_sound())

# 创建 Dog 和 Cat 对象
dog = Dog()
cat = Cat()

# 调用 make_sound 函数,传递不同的对象作为参数
make_sound(dog)  # 输出:Woof!
make_sound(cat)  # 输出:Meow!

不同的对象(Dog 和 Cat)对同一个方法(make_sound)作出了不同的响应,尽管它们是不同的类

相关推荐

  1. python 继承、封装

    2024-04-24 08:30:04       11 阅读
  2. python继承

    2024-04-24 08:30:04       13 阅读
  3. Python继承解释示例

    2024-04-24 08:30:04       14 阅读
  4. Python学习之-继承

    2024-04-24 08:30:04       17 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-24 08:30:04       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-24 08:30:04       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-24 08:30:04       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-24 08:30:04       18 阅读

热门阅读

  1. k8s的资源对象Deployment该如何使用?

    2024-04-24 08:30:04       13 阅读
  2. python读取pdf表格并合并为excel

    2024-04-24 08:30:04       16 阅读
  3. ILM ADO storage tiering policy on table partition

    2024-04-24 08:30:04       11 阅读
  4. Linux系统上C++使用alsa库播放声音文件

    2024-04-24 08:30:04       12 阅读
  5. 深度学习基础之《TensorFlow框架(14)—TFRecords》

    2024-04-24 08:30:04       14 阅读
  6. LeetCode //C - 29. Divide Two Integers

    2024-04-24 08:30:04       12 阅读
  7. 关于上传自己本地项目到GitHub的相关命令

    2024-04-24 08:30:04       12 阅读
  8. Unity UI擦除效果

    2024-04-24 08:30:04       12 阅读
  9. Rust:遍历 BinaryHeap

    2024-04-24 08:30:04       12 阅读