1. 程式人生 > >Python抽象類模擬介面

Python抽象類模擬介面

什麼是介面 ?

介面只是定義了一些方法,而沒有去實現,多用於程式設計時,只是設計需要有什麼樣的功能,但是並沒有實現任何功能,這些功能需要被另一個類(B)繼承後,由 類B去實現其中的某個功能或全部功能。

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

個人覺得介面在python中並沒有那麼重要,因為如果要繼承介面,需要把其中的每個方法全部實現,否則會報編譯錯誤,還不如直接定義一個class,其中的方法實現全部為pass,讓子類重寫這些函式。

當然如果有強制要求,必須所有的實現類都必須按照介面中的定義寫的話,就必須要用介面。

方法一:用抽象類和抽象函式實現方法

  1. #抽象類加抽象方法就等於面向物件程式設計中的介面

  2. from abc import ABCMeta,abstractmethod

  3. class interface(object):

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

  5. @abstractmethod #抽象方法

  6. def Lee(self):

  7. pass

  8. def Marlon(self):

  9. pass

  10. class RelalizeInterfaceLee(interface):#必須實現interface中的所有函式,否則會編譯錯誤

  11. def __init__(self):

  12. print '這是介面interface的實現'

  13. def Lee(self):

  14. print '實現Lee功能'

  15. def Marlon(self):

  16. pass

  17. class RelalizeInterfaceMarlon(interface): #必須實現interface中的所有函式,否則會編譯錯誤

  18. def __init__(self):

  19. print '這是介面interface的實現'

  20. def Lee(self):

  21. pass

  22. def Marlon(self):

  23. print "實現Marlon功能"

方法二:用普通類定義介面

  1. class interface(object): #假設這就是一個介面,介面名可以隨意定義,所有的子類不需要實現在這個類中的函式

  2. def Lee(self):,

  3. pass

  4. def Marlon(self):

  5. pass

  6. class Realaize_interface(interface):

  7. def __init__(self):

  8. pass

  9. def Lee(self):

  10. print "實現介面中的Lee函式"

  11. class Realaize_interface2(interface):

  12. def __init__(self):

  13. pass

  14. def Marlon(self):

  15. print "實現介面中的Marlon函式"

  16. obj=Realaize_interface()

  17. obj.Lee()

  18. obj=Realaize_interface2()

  19. obj.Marlon()