This article mainly introduces the new writing of Python abstract class, this article explained the old version of the hack way to implement the abstract class, and 2.7 use Abstractmethod module to write abstract class method, need friends can refer to the following
Remember the previous learn Python book, because there was no official support, only through the hack way to implement abstract methods, the following is the simplest method
?
| 1 2 3 4 5 6 7 8 9 10 11 |
Class Mycls (): def foo (self): example of the run of print (' method no implement ') >>> a = Mycls () >>> A.foo () metho D No implement >>> |
This can be used, but the hint is not obvious, or easy to misuse, of course, there are better ways to accept the wording
?
| 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 impleme NT ') |
This is what was written before 2.7, and 2.7 gives us the new support Method!ABC Module (abstruct base Class), which has been implemented in py3k, is the back port.
Let's take a look at the new wording.
?
| 1 2 3 4 5 6 7 8 9 |
From ABC import abcmeta from ABC import Abcmeta,abstractmethod class Foo (): __metaclass__ = Abcmeta @abstractmethod de F Bar (self): Pass |
Run effect
?
| 1 2 3 4 5 6 7 8 9/ |
>>> 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 Abstrac T class C with abstract methods bar >>> |