1. Abstract class Concepts
An abstract class is a special class that can only be inherited and cannot be instantiated
2. Why should there be abstract classes
In fact, in the non-contact abstract class concept, we can construct bananas, apples, pears and other classes, and then let them inherit the fruit of this base class, the fruit base class contains a eat function.
But have you ever thought that we can instantiate bananas, apples and pears and eat bananas, apples, pears. But we can't instantiate fruit, because we can't eat this thing called fruit.
So there can only be abstract methods in an abstract class (without implementing functionality), the class cannot be instantiated, it can only be inherited, and the subclass must implement an abstract method.
3. The role of abstract classes
In different modules by the abstract base class to invoke, you can use the most concise way to demonstrate the logic between the code, so that the dependencies between the module is clear and simple.
The programming of abstract classes allows everyone to focus on the methods and descriptions of the current abstract class without having to consider too much implementation detail, which is significant for collaborative development and makes code more readable.
4. Use of abstract classes
ImportAbc#implementing abstract classes with ABC modulesclassFile (METACLASS=ABC. Abcmeta):#ABC. Abcmeta is a basic class for implementing abstract classes@abc. Abstractmethod#define abstract methods without implementing functionality defRead (self):PassclassTXT (File):#subclass inherits the abstract class, but must define the Read method to overwrite the Read method in the abstract class defRead (self):Print('How to read text data') Txt1=Txt () txt1.read ()txt2=File () txt2.read ()
The operation results are as follows
method of reading text data Traceback (most recent call last): " e:/python/ftp_work/test.py " in <module> = File () typeerror:can't instantiate abstract Class File with abstract methods read
The abstract class is obviously instantiated with an error, and we get the results we want.
Compatibility issues with 5.ABC modules in python2&3
To address compatibility issues, we need to introduce six modules
|common practice. The role of the @six. Add_metaclass (Metaclass) is to provide an elegant metaclass of declaring classes between different versions of Python, in fact it can be used without it, but it is more neat and clear to use it.||Import six @six. Add_metaclass (Meta) class MyClass (object): pass|
|in Python 3 equivalent to||import Six class MyClass (object, Metaclass = Meta): pass|
|in Python 2.x (x >= 6) is equivalent to||import Six class MyClass (object): & nbsp;__metaclass__ = Meta pass|
|or just call the adorner, and here you can see that the adorner is just a way to wrap it.||Import Six class MyClass (object): passmyclass = six.add_metaclass (Meta) (MyClass)|