1. What is an interface
An interface can be understood as a portal to users to invoke their own functional methods.
2. Why to use the interface
(1). Permission control can be implemented, such as access control can be done through the interface, can allow or deny some of the caller's actions.
(2). Reduce the user's use of the difficulty, the user only need to know how to call, do not need to know the implementation method inside.
3. Examples of interfaces
classFile:#Defining Interfaces defRead (self):#Fixed interface function Read Pass defWrite (self):#defining an interface function write PassclassTXT (Interface):#text that implements read and write specifically defRead (self):Print('How to read text data') defWrite (self):Print('How to read text data')classSata (Interface):#disk, specifically implemented read and write defRead (self):Print('How to read hard disk data') defWrite (self):Print('How to read hard disk data')
The above example is an interface type, and the methods in the subclass are consistent with the parent class. However, this release does not force subclasses to have methods defined in the parent class, and subclasses can arbitrarily change the function name.
The "abstract class" is used to solve the above method.
Abstract class
ImportAbc#Import ABC module to implement abstract classclassIfile (METACLASS=ABC. Abcmeta):#fixed notation, the class name does not matter, can be arbitrarily taken.@abc. Abstractmethod#defines an abstract method, which must have the following function in the subclass of the inheriting class, without an error. defRead (self):Pass@abc. AbstractmethoddefWrite (self):PassclassTXT (Ifile):#subclass inherit abstract class subclass must have read and write method, no error. defRead (self):Print('This is the TXT file read') defWrite (self):Print('This is the TXT file's write :')classHtml (Ifile):defRead (self):Print('This is the reading of the HTML file') defWrite (self):Print('This is the write of the HTML file :') T= Txt ()#Defining Objectsh =Html () t.read ()#use the Read method directly when you use it. In this way, everyone is unified, read the file when you use the Read method. H.read ()
Python interface and normalized design + abstract class