Python abstract base class (ABC)

Source: Internet
Author: User

Setting the Abcmeta meta-class

An abstract class is a class that is used for inheritance, but does not need to implement a specific method, and it creates a method signature that some subclasses must implement. Abstract classes are useful in defining and enforcing class abstractions, similar to other interface concepts that become languages, without the need to implement specific methods.

Conceptually, one way to implement an abstract class is to stub the class method and then throw the Notimplementederror exception directly when the class method is accessed. This prevents subclasses from accessing the class method of the parent class directly before the class method is overridden.

Like this:

class Fruit:         def check_ripeness (self):         Raise Notimplementederror ("check_ripeness method not implemented! " )class  Apple (Fruit):    pass=# raises Notimplementederror

Creating abstract classes in this way prevents inappropriate use of class methods that have not been overridden, and we encourage the definition of these abstract class methods in subclasses, but they are not enforced. The ABC module prevents subclasses from being instantiated without successfully overriding the abstract class methods in the parent class and its ancestor classes.

 fromAbcImportAbcmetaclassAbstractClass (object):#The Metaclass property must be set to a class property    __metaclass__=Abcmeta#Abstractmethod decorator, used to register the method as an unbound method@abstractmethoddefVirtual_method_subclasses_must_define (self):#can directly not write, also can provide the basic realization       #Note that, in general, if you do not write it, it will implicitly return none,       #but by registering like this, it won't force a return to none.

Now you can simplify subclasses and override abstract class methods:

class Subclass (AbstractClass):     def Virtual_method_subclasses_must_define (self):         return ' whatever '

Why use Abcmeta and Abstractmethod, and how to use them

  Abstract base class (ABCs) forces derived classes to implement specific methods in the base class.

To understand how it works and why it is used, let's look at an example. For example, we have a base class "Montypython" with two methods (joke and punchline) that must be implemented in all derived classes:

class Montypython:     def joke (self):         Raise notimplementederror ()     def punchline (self):         Raise Notimplementederror () class argumentclinic (Montypython):     def joke (self):         return " Hahahahahah "

When we instantiate an object and call the two methods of it, the error will be given when calling punchline:

>>> sketch = argumentclinic ()  >>>

However, we can still instantiate the Argumentclinic class normally without any errors. In fact, we only get an error when we visit the punchline () method.

This problem does not occur if you use the abstract base class (ABC) module. Let's look at how it works in the following example:

 from  ABC import   Abcmeta, Abstractmethod  class  Montypython (Metaclass=abcmeta): @abstractmethod  def   joke (self):  pass   @abstractmethod  def   punchline (self):  pass  class   Argumentclinic (Montypython):  def   joke (self):  return   " hahahahahah   " 

Now when we instantiate this incomplete class, it will immediately report typeerrors Error!

>>> C = argumentclinic () TypeError:"Can ' t instantiate abstract class Argumentclinic with Abstract methods punchline"

In this case, we can typeerrors the two abstract classes by implementing the errors in the subclasses.

class argumentclinic (Montypython):     def joke (self):         return " Hahahahahah "    def punchline (self):         return " Send in the constable! "

Now, you can instantiate the Argumentclinic class as you normally would.

Python abstract base class (ABC)

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.