What is an interface?
Interface just defines some methods, but not to implement, more for the programming, but the design needs to what kind of function, but did not implement any function, these functions need to be inherited by another class (b), class B to implement one of these functions or all functions.
Personal understanding, more for collaborative development, there are different people in different classes to implement the various methods in the interface.
In Python, interfaces are implemented by abstract classes and abstract methods, interfaces cannot be instantiated, and can only be inherited by other classes to implement the corresponding functions.
Personally feel that the interface in Python is not so important, because if you want to inherit the interface, you need to implement each of the methods, otherwise it will report a compilation error, rather than directly define a class, where the method implementation is all pass, let subclasses rewrite these functions.
Of course, if there is a mandatory requirement, all of the implementation classes must be written in accordance with the definitions in the interface, and the interface must be used.
Method one: Using abstract classes and abstract functions to implement the method
#抽象类加抽象方法就等于面向对象编程中的接口from ABC Import Abcmeta,abstractmethodclass Interface (object): __metaclass__ = Abcmeta # Specifies that this is an abstract class @abstractmethod #抽象方法 def Lee: pass def Marlon (self): Passclass Relalizeinterfacelee (interface): #必须实现interface中的所有函数, otherwise compile error def __init__ (self): print ' This is the implementation of the interface interface ' def Lee: print ' implementation of the Lee function ' def Marlon (self): Pass class Relalizeinterfacemarlon (interface): #必须实现interface中的所有函数, otherwise compile error def __init__ (self): print ' This is the implementation of interface interface ' def Lee: pass def Marlon (self):
Method Two: Define the interface with the ordinary class,
Class Interface (object): #假设这就是一个接口, the interface name can be arbitrarily defined, all subclasses do not need to implement the function in this class def Lee (self):, pass def Marlon : Pass Class Realaize_interface (interface): def __init__ (self): pass def Lee: print " Implement the Lee function in the interface " class Realaize_interface2 (interface): def __init__ (self): pass def Marlon": print "Implements the Marlon function in the interface" obj=realaize_interface () obj. Lee () Obj=realaize_interface2 () obj. Marlon ()
Interfaces in Python