New Writing of the Python abstract class
This article mainly introduces the new writing method of the Python abstract class. This article explains how to implement the abstract class by using the hack method in the old version, and how to use the abstractmethod module to write the abstract class after 2.7. For more information, see
I remember in the previous book learn python, because there was no official support at the time, I could only use the hack method to implement the abstract method. The simplest method is as follows:
?
1 2 3 4 5 6 7 8 9 10 11 |
Class MyCls (): Def foo (self ): Print ('method no implement ') Running example >>> A = MyCls () >>> A. foo () Method no implement >>> |
Although this method can be used, but the prompt is not obvious, it is still easy to misuse. Of course, there are better ways to make it more acceptable.
?
1 2 3 |
Class MyCls (): Def foo (self ): Raise Exception ('no implement exception', 'foo method need implement ') |
A simple use case
?
1 2 3 4 5 6 |
>>> A = MyCls () >>> A. foo () Traceback (most recent call last ): File "<interactive input>", line 1, in <module> File "<clipboard>", line 3, in foo Exception: ('no implement exception', 'foo method need implement ') |
This is what we wrote before 2.7. 2.7 gave us a new support method! Abc module (abstruct base class), which has been implemented in py3k, is a back port.
Let's take a look at the new writing method.
?
1 2 3 4 5 6 7 8 9 |
From abc import ABCMeta From abc import ABCMeta, abstractmethod Class Foo (): _ Metaclass _ = ABCMeta @ Abstractmethod Def bar (self ): Pass |
Running Effect
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
>>> Class B (Foo ): ... Def bar (self ): ... Pass ... >>> B () <__ Main _. B object at 0x02EE7B50> >>> B (). bar () >>> Class C (Foo ): ... Pass ... >>> C (). bar () Traceback (most recent call last ): File "<interactive input>", line 1, in <module> TypeError: Can't instantiate abstract class C with abstract methods bar >>> |