Python抽象類模擬介面
什麼是介面 ?
介面只是定義了一些方法,而沒有去實現,多用於程式設計時,只是設計需要有什麼樣的功能,但是並沒有實現任何功能,這些功能需要被另一個類(B)繼承後,由 類B去實現其中的某個功能或全部功能。
在python中介面由抽象類和抽象方法去實現,介面是不能被例項化的,只能被別的類繼承去實現相應的功能。
個人覺得介面在python中並沒有那麼重要,因為如果要繼承介面,需要把其中的每個方法全部實現,否則會報編譯錯誤,還不如直接定義一個class,其中的方法實現全部為pass,讓子類重寫這些函式。
當然如果有強制要求,必須所有的實現類都必須按照介面中的定義寫的話,就必須要用介面。
方法一:用抽象類和抽象函式實現方法
-
#抽象類加抽象方法就等於面向物件程式設計中的介面
-
from abc import ABCMeta,abstractmethod
-
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功能"
方法二:用普通類定義介面
-
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()