python的多态意义吗_Python中的多态如何理解?(转帖,让我很理解。)

Python中多态的作用

让具有不同功能的函数可以使用相同的函数名,这样就可以用一个函数名调用不同内容(功能)的函数。

Python中多态的特点

1、只关心对象的实例方法是否同名,不关心对象所属的类型;

2、对象所属的类之间,继承关系可有可无;

3、多态的好处可以增加代码的外部调用灵活度,让代码更加通用,兼容性比较强;

4、多态是调用方法的技巧,不会影响到类的内部设计。

多态的应用场景

1. 对象所属的类之间没有继承关系

调用同一个函数fly(), 传入不同的参数(对象),可以达成不同的功能

class Duck(object):                                  # 鸭子类

def fly(self):

print("鸭子沿着地面飞起来了")

class Swan(object):                                  # 天鹅类

def fly(self):

print("天鹅在空中翱翔")

class Plane(object):                                 # 飞机类

def fly(self):

print("飞机隆隆地起飞了")

def fly(obj):                                        # 实现飞的功能函数

obj.fly()

duck = Duck()

fly(duck)

swan = Swan()

fly(swan)

plane = Plane()

fly(plane)

===运行结果:===================================================================================

鸭子沿着地面飞起来了

天鹅在空中翱翔

飞机隆隆地起飞了

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

2. 对象所属的类之间有继承关系(应用更广)

class gradapa(object):

def __init__(self,money):

self.money = money

def p(self):

print("this is gradapa")

class father(gradapa):

def __init__(self,money,job):

super().__init__(money)

self.job = job

def p(self):

print("this is father,我重写了父类的方法")

class mother(gradapa):

def __init__(self, money, job):

super().__init__(money)

self.job = job

def p(self):

print("this is mother,我重写了父类的方法")

return 100

#定义一个函数,函数调用类中的p()方法

def fc(obj):

obj.p()

gradapa1 = gradapa(3000)

father1 = father(2000,"工人")

mother1 = mother(1000,"老师")

fc(gradapa1)            #这里的多态性体现是向同一个函数,传递不同参数后,可以实现不同功能.

fc(father1)

print(fc(mother1))

===运行结果:===================================================================================

this is gradapa

this is father,我重写了父类的方法

this is mother,我重写了父类的方法

100

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

————————————————

版权声明:本文为CSDN博主「tigerlib」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。

原文链接:https://blog.csdn.net/weixin_44695969/article/details/92175840

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值