1. 程式人生 > >Python中的多型與虛擬函式

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.