這篇文章主要介紹了Python2和Python3中@abstractmethod使用方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
抽象方法:
抽象方法表示基類的一個(gè)方法,沒有實(shí)現(xiàn),所以基類不能實(shí)例化,子類實(shí)現(xiàn)了該抽象方法才能被實(shí)例化。
Python的abc提供了@abstractmethod裝飾器實(shí)現(xiàn)抽象方法,下面以Python3的abc模塊舉例。
@abstractmethod:
基類Foo的fun方法被@abstractmethod裝飾了,所以Foo不能被實(shí)例化;子類SubA沒有實(shí)現(xiàn)基類的fun方法也不能被實(shí)例化;子類SubB實(shí)現(xiàn)了基類的抽象方法fun所以能實(shí)例化。
完整代碼:
在Python3.4中,聲明抽象基類最簡(jiǎn)單的方式是子類話abc.ABC;Python3.0到Python3.3,必須在class語(yǔ)句中使用metaclass=ABCMeta;Python2中使用__metaclass__=ABCMeta
Python3.4 實(shí)現(xiàn)方法:
from abc import ABC, abstractmethod class Foo(ABC): @abstractmethod def fun(self): '''please Implemente in subclass''' class SubFoo(Foo): def fun(self): print('fun in SubFoo') a = SubFoo() a.fun()