33 ways to implement abstract base classes in Python __python

Source: Internet
Author: User

Python's abstract base class is similar to the concept of interfaces in object-oriented languages such as Java and C + +. Abstract base classes provide a way to require subclasses to implement a specified protocol, and an exception is thrown when an abstract base class requires that the specified method be implemented and the subclass is not implemented, when an attempt is made to create a subclass or execute a subclass code. Here's a brief description of three ways Python implements abstract base classes.


method One: Use Notimplementederror

See the following test code, only the subclass implements the Run method to run running.

>>>classTask ():def__init__ (self, x, y): self.x = x self.y = y >>>classTask ():def__init__ (self, x, y): self.x = x self.y = ydefRun (self):RaiseNotimplementederror (' Please define ' a Run method ') >>> t = Task (1, 2) >>> T.run () traceback (most rece NT call last): File "<pyshell#12>", line 1, in<module> T.run () File "<pyshell#10>", line 6, inRunRaiseNotimplementederror (' Please define ' a Run method ') notimplementederror:please define "a Run method" >>> >&gt ;>classSubTask(Task):def__init__ (self, x, y): Super (). __init__ (x, y)defRun(self): print (' Task (x=%s, y=%s) '% (self.x, self.y)) >>> st = SubTask (1, 3) >>> St.run () Task (x =1, y=3) >>>


method Two: Using the Meta class

Taskmeta (type):
    __new__ (CLS, name, bases, attrs):

        new_class = Super (Taskmeta, CLS). __new__ (CLS, name , bases, Attrs)

        False):
            new_class

        callable (new_ Class.run):
            typeerror (' Please define ' a Run method ')

        new_class


 Task (Metaclass=taskmeta):
    True

    __init__ (self, x, y):
        self.x = x
        self.y = y


SubTask (Task):
    __init__ (self, x, y):
        super (). _ _init__ (x, y)

    Run (self):
        print (' Task (x=%s, y=%s) '% (self.x, SELF.Y))

Test code One:

>>> t = Task (1, 3)
>>> t.run ()
Traceback (most recent call last):
  <module>
    T.run ()
Attributeerror: ' Task ' object has no attribute ' run '
>>> st = SubTask (1, 3)
>>> st.run ()
Ta SK (X=1, y=3)


This example is similar to method one, but there are some subtle differences. The first difference is that the task class itself can still be instantiated, but the run method is not running, otherwise a attributeerror error is thrown. The more important difference is in subclasses. When a subclass is created, the Meta class runs the __new__ method, and the interpreter says that no subclass of the Run method is allowed to be created.

SubTask (Task): ...    Pass
 ...
Traceback (most recent call last):
  <module>
    SubTask (Task):
  __new__
    TypeError (' Please define ' a Run method ') 
Typeerror:please define "a Run method"


method Three: Use @abstractmethod

The ABC module provides a mechanism for declaring protocols using an abstract base class, and subclasses must provide an implementation that conforms to the protocol.

ABC


Task (metaclass = abc. Abcmeta):
    __init__ (self, x, y):
        self.x = x
        self.y = y

    @abc. Abstractmethod
    Run ( Self):
        

pass SubTask(Task): _

     _init (self, x, y):
        super (). __init__ (x, y)

    Run (self):
        print (' Task (x=%s, y=%s) '% (self.x, SELF.Y))

othersubtask (Task):
    __init (self, x, y):
        super (). __init__ (x, y)

Similar to the example of method one, method two, but slightly different. First, the task class itself cannot be instantiated.

>>> T = Task (1, 3)
Traceback (most recent call last):
  <module>
    t = Task (1, 3)
Typ Eerror:can ' t instantiate abstract class Task with abstract methods run


This differs from the method, which allows the base class task to be instantiated.

For subclasses that do not rewrite the Run method correctly, it differs from the previous two methods in the wrong case. Method One, the notimplementederror is used to eventually cause a notimplementederror error when the Run method is invoked. In method Two, a custom Taskmeta class is used, which throws a typeerror error when the abstract class is created.

When a subclass of the Run method is not instantiated, the error message is given in the same way that it was given when the task class was instantiated, logically fully in line with expectations.

>>> ot = Othersubtask (1, 3)
Traceback (most recent call last):
  <module>
    ot = Othersubtask (1, 3)
Typeerror:can ' t instantiate abstract class Othersubtask with abstract methods run
However, when you define a subclass of the Run method, the subclass can be instantiated to work correctly.

>>> st = SubTask (1, 3)
>>> st.run ()
Task (x=1, y=3)



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.