Learn Python's ABC module (GO)

Source: Internet
Author: User

Http://yansu.org/2013/06/09/learn-Python-abc-module.html

1.ABC module function

Python itself does not provide abstract classes and interface mechanisms, and to implement abstract classes, you can use the ABC module. ABC is the abbreviation for abstract Base class.

2. Class and function ABC in the module. Abcmeta

This is the meta-class used to generate the abstract base class. The classes generated by it can be inherited directly.

FromAbcImport abcmetaclass myabc: __metaclass__ = abcmetamyabc. (tuple Issubclass (tuple myabc) assert  Isinstance ((),  myabc)   

In the above example, a MYABC abstract base class is generated, and then the tuple is transformed into its virtual subclass. Then either Issubclass or isinstance can determine whether a tuple is out of the Myabc class.

In addition, the same functionality can be achieved by means __subclasshook__(subclass) of replication, which must be Classmethod

Class Foo(Object): Def__getitem__(Self,Index): ... Def__len__(Self): ... DefGet_iterator(Self): ReturnIter(Self)Class Myiterable:__metaclass__= Abcmeta @abstractmethod Def__iter__(Self): While False: Yield None DefGet_iterator(Self): Return Self.__iter__() @classmethod Def__subclasshook__(Cls,C): IfClsIs myiterable: if Any ( "__iter__"  in  B.for B in C.< Span class= "PLN" >__mro__):  return true return notimplemented< Span class= "PLN" >myiterable. (foo)        
Abc.abstractmethod (function)

The generator that indicates the abstract method

class C:    __metaclass__ = ABCMeta @abstractmethod def my_abstract_method(self, ...): ...
Abc.abstractproperty ([Fget[,fset[,fdel[,doc]])

Indicates an abstract property

class C:    __metaclass__ = ABCMeta @abstractproperty def my_abstract_property(self): ...

The previous example is just a read-only property, and if it is a read-write property, you can:

class C: __ metaclass__ = abcmeta  Getx (self  ...  def Setx (self, Value):   ...  x = Abstractproperty ( Getx, Setx)        

Learning Python's ABC module (GO)

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.