前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python中的多态与虚函数

Python中的多态与虚函数

作者头像
py3study
发布2020-01-09 11:31:38
1.6K0
发布2020-01-09 11:31:38
举报
文章被收录于专栏:python3python3

   C++中的虚函数与多态,是很多C++面向对象程序设计的一个基础,在Python中,是否也存在多态和虚函数,答案是有的。看下面的这个例子

代码语言:javascript
复制
from abc import ABCMeta, abstractmethod


class Base():
    __metaclass__ = ABCMeta

    def __init__(self):
        pass

    @abstractmethod
    def get(self):
        print "Base.get()"
        pass


class Derive1(Base):
    def get(self):
        print "Derive1.get()"


class Derive2(Base):
    def get(self):
        print "Derive2.get()"


if __name__ == '__main__':
    b = Base()
    b.get()

运行的时候,提示:

    b = Base() TypeError: Can't instantiate abstract class Base with abstract methods get

如果分别构建两个子类的对象,则

代码语言:javascript
复制
if __name__ == '__main__':
    b = Derive1()
    c = Derive2()
    b.get()
    c.get()

运行结果:

Derive1.get() Derive2.get()

从上面的例子可以看出,代码已经具备C++中多态和虚函数的特点了

那么,Python是如何做到这点的?

1.abc module

在代码中,首先

代码语言:javascript
复制
from abc import ABCMeta, abstractmethod

python 文档对于abc是这么定义的


This module provides the infrastructure for defining abstract base classes (ABCs) in Python

2. 声明 metaclass

代码语言:javascript
复制
__metaclass__ = ABCMeta

Use this metaclass to create an ABC. An ABC can be subclassed directly, and then acts as a mix-in class

关于metaclass的定义,可以参见http://jianpx.iteye.com/blog/908121

3.申明函数为虚函数

代码语言:javascript
复制
@abstractmethod

A decorator indicating abstract methods.

Using this decorator requires that the class’s metaclass is ABCMeta or is derived from it. A class that has a metaclass derived from ABCMeta cannot be instantiated unless all of its abstract methods and properties are overridden. The abstract methods can be called using any of the normal ‘super’ call mechanisms.

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-08-30 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
前端性能监控
前端性能监控(Real User Monitoring,RUM)是一站式前端监控解决方案,专注于 Web、小程序等场景监控。前端性能监控聚焦用户页面性能(页面测速,接口测速,CDN 测速等)和质量(JS 错误,Ajax 错误等),并且联动腾讯云应用性能监控实现前后端一体化监控。用户只需要安装 SDK 到自己的项目中,通过简单配置化,即可实现对用户页面质量的全方位守护,真正做到低成本使用和无侵入监控。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档