Python 3.6:多态的实现


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

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

实际上C++使用VPTR指针来完成这个事情,其是设计模式的基础,软件分层的基石。最近看了一下Python,很欣慰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

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

微信.jpg

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值