1 要有继承
2 要有虚函数函数重写
3 要有父类指针(父类引用)指向子类对象
实际上C++使用VPTR指针来完成这个事情,其是设计模式的基础,软件分层的基石。
最近看了一下Pyhon,很欣慰python3.6(因为我学的时候已经是3.6了)中支持不错,基
本也是遵循C++的3个要点需要模块支持如下:
from abc import ABC,abstractmethod
代码如下:
抽象类:
点击(此处)折叠或打开
-
#在C++中使用如下3个条件实现多态
-
#1、虚函数从写
-
#2、父类指针指向子类对象
-
#3、继承
-
#python 3.6中也可以使用方便使用抽象类 from abc import ABC,abstractmethod
-
from abc import ABC, abstractmethod
-
-
class Handller(ABC): ##抽象类
-
@abstractmethod ##指定为接口函数 类似C++的纯虚函数
-
def test(self):
- pass
实现类:
点击(此处)折叠或打开
-
import ABC
-
part = 0
-
#两个类继承来自同一个抽象类
-
class Child_1(ABC.Handller): #继承
-
def __init__(self,b,c):
-
self.name = b
-
self.age = c
-
def test(self): #类似C++虚函数重写函数
-
print("this is test {} {}".format(self.name,self.age))
-
class Child_2(ABC.Handller): #继承
-
a = 0
-
def __init__(self,a):
-
self.name = a
-
def test(self): #类似C++虚函数重写函数
-
print("this is test {}".format(self.name))
-
class Do_thing():
-
@staticmethod
-
def test_do_thing(handler): #统一调用接口
- handler.test()
-
-
a = Child_1('gaopeng',30)
-
b = Child_2('gaopeng')
-
Do_thing.test_do_thing(a) ##多态 父类指针指向子类对象
- Do_thing.test_do_thing(b) ##多态 父类指针指向子类对象
运行结果:
this is test gaopeng 30
this is test gaopeng
简短测试但是麻雀虽小五脏俱全。