在Python中定義和使用抽象類的方法
像java一樣python也可以定義一個抽象類。
在講抽象類之前,先說下抽象方法的實現(xiàn)。
抽象方法是基類中定義的方法,但卻沒有任何實現(xiàn)。在java中,可以把方法申明成一個接口。而在python中實現(xiàn)一個抽象方法的簡單的方法是:
class Sheep(object): def get_size(self): raise NotImplementedError
任何從Sheep繼承下來的子類必須實現(xiàn)get_size方法。否則就會產(chǎn)生一個錯誤。但這種實現(xiàn)方法有個缺點。定義的子類只有調(diào)用那個方法時才會拋錯。這里有個簡單方法可以在類被實例化后觸發(fā)它。使用python提供的abc模塊。
import abc class Sheep(object): __metaclass__ = abc.ABCMeta @abc.absractmethod def get_size(self): return
這里實例化Sheep類或任意從其繼承的子類(未實現(xiàn)get_size)時候都會拋出異常。
因此,通過定義抽象類,可以定義子類的共同method(強制其實現(xiàn))。
如何使用抽象類
import abc class A(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def load(self, input): return @abc.abstractmethod def save(self, output, data): return
通過ABCMeta元類來創(chuàng)建一個抽象類, 使用abstractmethod裝飾器來表明抽象方法
注冊具體類
class B(object): def load(self, input): return input.read() def save(self, output, data): return output.write(data) A.register(B) if __name__ == '__main__': print issubclass(B, A) # print True print isinstance(B(), A) # print True
從抽象類注冊一個具體的類
子類化實現(xiàn)
class C(A): def load(self, input): return input.read() def save(self, output, data): return output.write(data) if __name__ == '__main__': print issubclass(C, A) # print True print isinstance(C(), A) # print True
可以使用繼承抽象類的方法來實現(xiàn)具體類這樣可以避免使用register. 但是副作用是可以通過基類找出所有的具體類
for sc in A.__subclasses__(): print sc.__name__ # print C
如果使用繼承的方式會找出所有的具體類,如果使用register的方式則不會被找出
使用__subclasshook__
使用__subclasshook__后只要具體類定義了與抽象類相同的方法就認為是他的子類
import abc class A(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def say(self): return 'say yeah' @classmethod def __subclasshook__(cls, C): if cls is A: if any("say" in B.__dict__ for B in C.__mro__): return True return NotTmplementd class B(object): def say(self): return 'hello' print issubclass(B, A) # True print isinstance(B(), A) # True print B.__dict__ # {'say': <function say at 0x7f...>, ...} print A.__subclasshook__(B) # True
不完整的實現(xiàn)
class D(A): def save(self, output, data): return output.write(data) if __name__ == '__main__': print issubclass(D, A) # print True print isinstance(D(), A) # raise TypeError
如果構(gòu)建不完整的具體類會拋出D不能實例化抽象類和抽象方法
具體類中使用抽象基類
import abc from cStringIO import StringIO class A(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def retrieve_values(self, input): pirnt 'base class reading data' return input.read() class B(A): def retrieve_values(self, input): base_data = super(B, self).retrieve_values(input) print 'subclass sorting data' response = sorted(base_data.splitlines()) return response input = StringIO("""line one line two line three """) reader = B() print reader.retrieve_values(input)
打印結(jié)果
base class reading data subclass sorting data ['line one', 'line two', 'line three']
可以使用super來重用抽象基類中的羅輯, 但會迫使子類提供覆蓋方法.
抽象屬性
import abc class A(object): __metaclass__ = abc.ABCMeta @abc.abstractproperty def value(self): return 'should never get here.' class B(A): @property def value(self): return 'concrete property.' try: a = A() print 'A.value', a.value except Exception, err: print 'Error: ', str(err) b = B() print 'B.value', b.value
打印結(jié)果,A不能被實例化,因為只有一個抽象的property getter method.
Error: ... print concrete property
定義抽象的讀寫屬性
import abc class A(object): __metaclass__ = abc.ABCMeta def value_getter(self): return 'Should never see this.' def value_setter(self, value): return value = abc.abstractproperty(value_getter, value_setter) class B(A): @abc.abstractproperty def value(self): return 'read-only' class C(A): _value = 'default value' def value_getter(self): return self._value def value_setter(self, value): self._value = value value = property(value_getter, value_setter) try: a = A() print a.value except Exception, err: print str(err) try: b = B() print b.value except Exception, err: print str(err) c = C() print c.value c.value = 'hello' print c.value
打印結(jié)果, 定義具體類的property時必須與抽象的abstract property相同。如果只覆蓋其中一個將不會工作.
error: ... error: ... print 'default value' print 'hello'
使用裝飾器語法來實現(xiàn)讀寫的抽象屬性, 讀和寫的方法應(yīng)該相同.
import abc class A(object): __metaclass__ = abc.ABCMeta @abc.abstractproperty def value(self): return 'should never see this.' @value.setter def value(self, _value): return class B(A): _value = 'default' @property def value(self): return self._value @value.setter def value(self, _value): self._value = _value b = B() print b.value # print 'default' b.value = 'hello' print b.value # print 'hello'
相關(guān)文章
使用python創(chuàng)建股票的時間序列可視化分析
這篇文章主要為大家詳細介紹了python創(chuàng)建股票的時間序列可視化分析,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-03-03使用PyCharm配合部署Python的Django框架的配置紀實
這篇文章主要介紹了使用PyCharm配合部署Python的Django框架的配置紀實,PyCharm是一款強大的Python的IDE,需要的朋友可以參考下2015-11-11深入學(xué)習(xí)python的yield和generator
這篇文章主要為大家詳細介紹了python的yield和generator,針對python的生成器和yield關(guān)鍵字進行深入學(xué)習(xí),感興趣的小伙伴們可以參考一下2016-03-03Python上下文管理器類和上下文管理器裝飾器contextmanager用法實例分析
這篇文章主要介紹了Python上下文管理器類和上下文管理器裝飾器contextmanager用法,結(jié)合實例形式分析了上下文管理器類定義、使用、sqlalchemy實現(xiàn)數(shù)據(jù)庫的自動提交和回滾相關(guān)操作技巧,需要的朋友可以參考下2019-11-11- Python由荷蘭數(shù)學(xué)和計算機科學(xué)研究學(xué)會的Guido van Rossum 于1990 年代初設(shè)計,作為一門叫做ABC語言的替代品。 Python提供了高效的高級數(shù)據(jù)結(jié)構(gòu),還能簡單有效地面向?qū)ο缶幊?/div> 2021-10-10
Python實現(xiàn)嵌套列表的7中方法總結(jié)
這篇文章主要來給大家講解一個Python的進階知識點:如何將一個嵌套的大列表展開形成一個列表。小編提供了7種方法供大家學(xué)習(xí)參考,希望大家能喜歡2023-03-03最新評論