ABC is a class that cannot be instantiated. Python 3 Adds a new framework-abc-it provides support for ABC. This ABC module has a meta class ( ABCMeta
) and modifier ( @abstractmethod
and @abstractproperty
). If an ABC has one @abstractmethod
or @abstractproperty
, it cannot be instantiated, but must be overridden within a subclass. For example, the following code:
#-*-coding:utf-8-*- fromAbcImportAbcmeta,abstractmethod#Abstract classclassA (object):__metaclass__=Abcmeta @abstractmethoddefFun (self):Pass@abstractmethoddef_f (self):Pass #@abstractmethod Private method cannot be an abstract method def __f(self):Pass#Implementation ClassclassB (A):defFun (self,name):Print 'B for%s'%namedef_f (self,name):Print 'B for%s'%namedef __f(self,name):return 'B for%s'%namedefDo (self,name):PrintSelf.__f(name)#A=a () abstract class cannot be instantiatedb=B () b.fun ('YBF') B.fun ('Yyj')#B.__f () cannot be calledB.do ('Ybf&yyj')
Output:
B for YBF
B for Yyj
B for Ybf&yyj
If the subclass does not implement a method of the parent class, an error occurs. If not clear _, __, __xx__ difference, see here: Python _, __, __xx__ difference between.
Implementation of Python abstract class and abstract method