New Writing of the Python abstract class and the writing of the Python abstract class
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:
Class MyCls (): def foo (self): print ('method no implement ') running example >>> a = MyCls () >>>. 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.
class MyCls(): def foo(self): raise Exception('no implement exception', 'foo method need implement')
A simple use case
>>> a = MyCls()>>> a.foo()Traceback (most recent call last): File "<interactive input>", line 1, in <module> File "<clipboard>", line 3, in fooException: ('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.
from abc import ABCMeta from abc import ABCMeta,abstractmethod class Foo(): __metaclass__ = ABCMeta @abstractmethod def bar(self): pass
Running Effect
>>> 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>>>