什麼是接口 ?python
接口只是定義了一些方法,而沒有去實現,多用於程序設計時,只是設計須要有什麼樣的功能,可是並無實現任何功能,這些功能須要被另外一個類(B)繼承後,由 類B去實現其中的某個功能或所有功能。編程
我的的理解,多用於協做開發時,有不一樣的人在不一樣的類中實現接口中的各個方法。ide
在python中接口由抽象類和抽象方法去實現,接口是不能被實例化的,只能被別的類繼承去實現相應的功能。函數
我的以爲接口在python中並無那麼重要,由於若是要繼承接口,須要把其中的每一個方法所有實現,不然會報編譯錯誤,還不如直接定義一個class,其中的方法實現所有爲pass,讓子類重寫這些函數。spa
固然若是有強制要求,必須全部的實現類都必須按照接口中的定義寫的話,就必需要用接口。.net
方法一:用抽象類和抽象函數實現方法設計
[python] view plaincopycode
#抽象類加抽象方法就等於面向對象編程中的接口 對象
from abc import ABCMeta,abstractmethod blog
class interface(object):
__metaclass__ = ABCMeta #指定這是一個抽象類
@abstractmethod #抽象方法
def Lee(self):
pass
def Marlon(self):
pass
class RelalizeInterfaceLee(interface):#必須實現interface中的全部函數,不然會編譯錯誤
def __init__(self):
print '這是接口interface的實現'
def Lee(self):
print '實現Lee功能'
def Marlon(self):
pass
class RelalizeInterfaceMarlon(interface): #必須實現interface中的全部函數,不然會編譯錯誤
def __init__(self):
print '這是接口interface的實現'
def Lee(self):
pass
def Marlon(self):
print "實現Marlon功能"
方法二:用普通類定義接口,
[python] view plaincopy
class interface(object): #假設這就是一個接口,接口名能夠隨意定義,全部的子類不須要實如今這個類中的函數
def Lee(self):,
pass
def Marlon(self):
pass
class Realaize_interface(interface):
def __init__(self):
pass
def Lee(self):
print "實現接口中的Lee函數"
class Realaize_interface2(interface):
def __init__(self):
pass
def Marlon(self):
print "實現接口中的Marlon函數"
obj=Realaize_interface()
obj.Lee()
obj=Realaize_interface2()
obj.Marlon()