What is an interface ?
The interface just defines some methods , Instead of realizing it , It is often used in programming , It's just the function of design , But it doesn't do anything , These functions need to be implemented by another class （B） After Succession , from
class B To achieve one or all of these functions .
follow ： Open and closed principle , The principle of dependence , Interface isolation principle , Inheritance polymorphism .
Programming ideas ： Specification for subclasses ; Normalization design ： Several classes implement the same method
abstract class ： It's better to inherit alone , And it can realize the function simply , Interface class ： You can inherit more , And it is better not to achieve specific functions
stay python The interface is implemented by abstract class and abstract method , Interfaces cannot be instantiated , It can only be inherited by other classes to implement the corresponding functions .
I feel that the interface is python It's not that important , Because if you want to inherit the interface , You need to implement all of them , Otherwise, a compilation error will be reported , It's better to define one directly class, All the methods are implemented as follows pass, Let subclasses override these functions .
Method 1 ： Using abstract class and abstract function to realize method （ Applicable to single inheritance ）
# Abstract class plus abstract method is equivalent to the interface in object-oriented programming from abc import ABCMeta,abstractmethod class
interface(object): __metaclass__ = ABCMeta # Specifies that this is an abstract class @abstractmethod # Abstract method def
Lee(self): pass def Marlon(self): pass class
RelalizeInterfaceLee(interface):# Must be realized interface All functions in , Otherwise, compilation errors will occur def
__init__(self): print ' This is the interface interface Implementation of ' def Lee(self): print ' realization Lee function ' def
Marlon(self): pass class RelalizeInterfaceMarlon(interface):
# Must be realized interface All functions in , Otherwise, compilation errors will occur def __init__(self): print ' This is the interface interface Implementation of ' def
Lee(self): pass def Marlon(self): print " realization Marlon function "
Method 2 ： Defining interfaces with common classes （ recommend ）
class interface(object): # Suppose this is an interface , The interface name can be defined at will , All subclasses do not need to implement functions in this class def
Lee(self):, pass def Marlon(self): pass class Realaize_interface(interface):
def __init__(self): pass def Lee(self): print " Implement the Lee function " class
Realaize_interface2(interface): def __init__(self): pass def Marlon(self):
print " Implement the Marlon function " obj=Realaize_interface() obj.Lee()