python实现多态_Python

本文介绍了Python中的多态概念,包括多态性定义、优点和两种实现方式:通过继承和给函数传递不同参数。通过实例展示了如何创建Animal、Cat、Dog类并实现多态效果,使同一函数调用不同类的方法。
摘要由CSDN通过智能技术生成

Python多态教程

多态就是一种事物的多种体现形式,

什么是多态性

多态性是指具有不同功能的

Python多态的优点

增加了程序的灵活性:以不变应万变,不论对象千变万化,使用者都是同一种形式去调用。

增加了程序的可扩展性:即使是调用程序的对象变了,只要是继承自同一个父类,代码就不用做任何修改。

案例

Python多态

使用继承,实现多态

print("嗨客网(www.haicoder.net)")

class Animal:

def eat(self):

print("I like eat anything")

class Cat(Animal):

def eat(self):

print("I am a cat, and i just like eat finish")

class Dog(Animal):

def eat(self):

print("I am a dog, and i just like eat bone")

animal = Animal()

animal.eat()

animal = Cat()

animal.eat()

animal = Dog()

animal.eat()

程序运行后,控制台输出如下:

我们首先定义了一个 Animal 类,Animal 类有一个 eat 方法,接着,定义了一个 Cat 类和一个 Dog 类,Cat 类和 Dog 类都继承自 Animal 类。

Animal 类有一个 eat 方法,同时,Cat 类和 Dog 类也都有一个跟 Animal 类一模一样的 eat 方法,最后,我们首先实例化了一个 Animal 类,并调用了 Animal 类实例 animal 的 eat 方法。

接着,我们又同时实例化了一个 Cat 类和一个 Dog 类,并且都赋值给了 animal 对象,最后,我们发现,通过实例化不同的 animal 对象,我们分别实现了调用了 Animal、Dog 和 Cat 三个类的 eat 方法。

这就是继承实现了多态,同一个对象,不同的实例化,调用相同的函数,实现了调用不同类的函数。

Python多态

给函数传递不同的参数,实现多态

print("嗨客网(www.haicoder.net)")

class Animal:

def eat(self, animal):

animal.eat()

class Cat(Animal):

def eat(self):

print("I am a cat, and i just like eat finish")

class Dog(Animal):

def eat(self):

print("I am a dog, and i just like eat bone")

cat = Cat()

dog = Dog()

animal = Animal()

animal.eat(cat)

animal.eat(dog)

程序运行后,控制台输出如下:

我们在 Animal 类里面定义了一个 eat 方法,eat 方法接受两个参数,一个 self,一个是 animal 类型的对象,在 eat 方法里,我们直接调用了 animal 类型的对象的 eat 方法。

接着,我们定义了一个 Cat 类和一个 Dog 类,并且 Cat 类和 Dog 类都各自定义了 eat 方法,最后,我们实例化了一个 Cat 对象、一个 Dog 对象和一个 Animal 对象。

最后,我们分别将 cat 和 dog 实例传进 Animal 实例,实现了同一个函数,调用了 cat 和 dog 实例的 eat 方法。

Python多态教程

多态就是一种事物的多种体现形式,函数的重写其实就是多态的一种体现,在 Python 中,多态指的是父类的引用指向子类的对象。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值