Implementation of Python abstract class and abstract method

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.