python接口的定義

什麼是接口 ?python

接口只是定義了一些方法,而沒有去實現,多用於程序設計時,只是設計須要有什麼樣的功能,可是並無實現任何功能,這些功能須要被另外一個類(B)繼承後,由 類B去實現其中的某個功能或所有功能。編程

我的的理解,多用於協做開發時,有不一樣的人在不一樣的類中實現接口中的各個方法。ide

在python中接口由抽象類和抽象方法去實現,接口是不能被實例化的,只能被別的類繼承去實現相應的功能。函數

我的以爲接口在python中並無那麼重要,由於若是要繼承接口,須要把其中的每一個方法所有實現,不然會報編譯錯誤,還不如直接定義一個class,其中的方法實現所有爲pass,讓子類重寫這些函數。spa

固然若是有強制要求,必須全部的實現類都必須按照接口中的定義寫的話,就必需要用接口。.net

方法一:用抽象類和抽象函數實現方法設計

[python] view plaincopy在CODE上查看代碼片派生到個人代碼片code

  1. #抽象類加抽象方法就等於面向對象編程中的接口  對象

  2. from abc import ABCMeta,abstractmethod  blog

  3.   

  4. class interface(object):  

  5.     __metaclass__ = ABCMeta #指定這是一個抽象類  

  6.     @abstractmethod  #抽象方法  

  7.     def Lee(self):  

  8.         pass  

  9.       

  10.     def Marlon(self):  

  11.         pass  

  12.   

  13.   

  14. class RelalizeInterfaceLee(interface):#必須實現interface中的全部函數,不然會編譯錯誤  

  15.     def __init__(self):      

  16.         print '這是接口interface的實現'  

  17.     def Lee(self):  

  18.         print '實現Lee功能'          

  19.     def Marlon(self):  

  20.         pass     

  21.    

  22.   

  23. class RelalizeInterfaceMarlon(interface): #必須實現interface中的全部函數,不然會編譯錯誤  

  24.     def __init__(self):      

  25.         print '這是接口interface的實現'  

  26.     def Lee(self):  

  27.         pass        

  28.     def Marlon(self):  

  29.         print "實現Marlon功能"  

  30.    


方法二:用普通類定義接口,

[python] view plaincopy在CODE上查看代碼片派生到個人代碼片

  1. class interface(object): #假設這就是一個接口,接口名能夠隨意定義,全部的子類不須要實如今這個類中的函數  

  2.     def Lee(self):,  

  3.         pass  

  4.       

  5.     def Marlon(self):  

  6.         pass  

  7.    

  8. class Realaize_interface(interface):  

  9.     def __init__(self):  

  10.         pass  

  11.     def Lee(self):  

  12.         print "實現接口中的Lee函數"  

  13.           

  14.           

  15. class Realaize_interface2(interface):  

  16.     def __init__(self):  

  17.         pass  

  18.     def Marlon(self):  

  19.         print "實現接口中的Marlon函數"  

  20.        

  21. obj=Realaize_interface()  

  22. obj.Lee()  

  23.   

  24.   

  25. obj=Realaize_interface2()  

  26. obj.Marlon() 

相關文章
相關標籤/搜索