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()


轉載:http://blog.csdn.net/kobeyan/article/details/44344087

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章