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 

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



请使用浏览器的分享功能分享到微信等