Python 3.6:多态的实现

多态的作用不用多说,C++用如下条件来实现多态:

1 要有继承
2 要有虚函数函数重写
3 要有父类指针(父类引用)指向子类对象

实际上C++使用VPTR指针来完成这个事情,其是设计模式的基础,软件分层的基石。
最近看了一下Pyhon,很欣慰python3.6(因为我学的时候已经是3.6了)中支持不错,基
本也是遵循C++的3个要点需要模块支持如下:
from abc import ABC , abstractmethod
代码如下:

抽象类:

点击(此处)折叠或打开

  1. #在C++中使用如下3个条件实现多态
  2. #1、虚函数从写
  3. #2、父类指针指向子类对象
  4. #3、继承
  5. #python 3.6中也可以使用方便使用抽象类 from abc import ABC,abstractmethod
  6. from abc import ABC, abstractmethod

  7. class Handller(ABC): ##抽象类
  8.     @abstractmethod ##指定为接口函数 类似C++的纯虚函数
  9.     def test(self):
  10.         pass

实现类:


点击(此处)折叠或打开

  1. import ABC
  2. part = 0
  3. #两个类继承来自同一个抽象类
  4. class Child_1(ABC.Handller): #继承
  5.     def __init__(self,b,c):
  6.         self.name = b
  7.         self.age = c
  8.     def test(self): #类似C++虚函数重写函数
  9.         print("this is test {} {}".format(self.name,self.age))
  10. class Child_2(ABC.Handller): #继承
  11.     a = 0
  12.     def __init__(self,a):
  13.         self.name = a
  14.     def test(self): #类似C++虚函数重写函数
  15.         print("this is test {}".format(self.name))
  16. class Do_thing():
  17.     @staticmethod
  18.     def test_do_thing(handler): #统一调用接口
  19.         handler.test()

  20. a = Child_1('gaopeng',30)
  21. b = Child_2('gaopeng')
  22. Do_thing.test_do_thing(a) ##多态 父类指针指向子类对象
  23. Do_thing.test_do_thing(b) ##多态 父类指针指向子类对象

运行结果:

this is test gaopeng 30
this is test gaopeng 

简短测试但是麻雀虽小五脏俱全。

270


来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/7728585/viewspace-2151873/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/7728585/viewspace-2151873/

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值