Python中的多态与虚函数

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

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


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

if __name__ == '__main__':
    b = Derive1()
    c = Derive2()
    b.get()
    c.get()

运行结果:

Derive1.get()
Derive2.get()


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


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


1.abc module

在代码中,首先

from abc import ABCMeta, abstractmethod
python 文档对于abc是这么定义的


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


2. 声明 metaclass

__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.申明函数为虚函数

@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.









  • 5
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
好的,我可以为您介绍一下关于C++函数的实验。 首先,多是指不同对象以不同的方式响应相同的消息的能力。在C++,通过函数来实现多函数是指在基类被声明为函数函数,在派生类被重写后,在程序使用基类指针或引用调用该函数时,会调用派生类函数。 下面是一个简单的多函数的实验示例: ```c++ #include<iostream> using namespace std; class Shape { public: virtual void draw() { cout << "Drawing Shape" << endl; } }; class Circle: public Shape { public: void draw() { cout << "Drawing Circle" << endl; } }; class Square: public Shape { public: void draw() { cout << "Drawing Square" << endl; } }; int main() { Shape *s; Circle c; Square sq; s = &c; s->draw(); s = &sq; s->draw(); return 0; } ``` 运行结果为: ``` Drawing Circle Drawing Square ``` 在上述示例,我们定义了一个基类Shape和两个派生类Circle和Square,分别重写了基类的函数draw()。在程序,我们先定义了一个基类指针s,然后将其指向第一个派生类对象c,再调用s的函数draw(),此时会调用派生类Circle的draw()函数,因为指针实际上指向的是Circle类型的对象。接着,我们将指针s重新指向第二个派生类对象sq,再次调用s的函数draw(),此时会调用派生类Square的draw()函数。 通过这个实验,我们可以看到多函数的特性,即通过基类指针或引用调用函数时,会根据实际对象的类型来调用相应的派生类函数

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值