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.
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341