开发者社区> 问答> 正文

python 为什么没有虚函数

python 为什么没有虚函数

展开
收起
云计算小粉 2018-05-10 20:11:06 2833 0
2 条回答
写回答
取消 提交回答
  • python有lambda匿名函数。 还有type元类。

    2019-11-05 15:34:29
    赞同 展开评论 打赏
  • C++中的虚函数与多态,是很多C++面向对象程序设计的一个基础,在Python中,是否也存在多态和虚函数,答案是有的。看下面的这个例子

    [python] view plain copy
    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

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

    [python] view plain copy
    if name == '__main__':

    b = Derive1()  
    c = Derive2()  
    b.get()  
    c.get()  
    

    运行结果:
    Derive1.get()
    Derive2.get()

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

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

    1.abc module

    在代码中,首先

    [python] view plain copy
    from abc import ABCMeta, abstractmethod
    python 文档对于abc是这么定义的
    This module provides the infrastructure for defining abstract base classes (ABCs) in Python

    1. 声明 metaclass

    [python] view plain copy
    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.申明函数为虚函数

    [python] view plain copy
    @abstractmethod

    2019-07-17 22:25:42
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Python系列直播第一讲——Python中的一切皆对象 立即下载
低代码开发师(初级)实战教程 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载