日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:collections.abc—-容器的抽象基類

collections.abc —- 容器的抽象基類

3.3 新版功能: 該模塊曾是 collections 模塊的組成部分。

成都創(chuàng)新互聯(lián)公司于2013年開始,先為棲霞等服務(wù)建站,棲霞等地企業(yè),進行企業(yè)商務(wù)咨詢服務(wù)。為棲霞企業(yè)網(wǎng)站制作PC+手機+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問題。

源代碼: Lib/_collections_abc.py


該模塊定義了一些 抽象基類,它們可用于判斷一個具體類是否具有某一特定的接口;例如,這個類是否可哈希,或其是否為映射類。

一個接口的 issubclass() 或 isinstance() 測試采用以下三種方式之一。

1) A newly written class can inherit directly from one of the abstract base classes. The class must supply the required abstract methods. The remaining mixin methods come from inheritance and can be overridden if desired. Other methods may be added as needed:

 
 
 
 
  1. class C(Sequence): # Direct inheritance
  2. def __init__(self): ... # Extra method not required by the ABC
  3. def __getitem__(self, index): ... # Required abstract method
  4. def __len__(self): ... # Required abstract method
  5. def count(self, value): ... # Optionally override a mixin method
 
 
 
 
  1. >>> issubclass(C, Sequence)
  2. True
  3. >>> isinstance(C(), Sequence)
  4. True

2) Existing classes and built-in classes can be registered as “virtual subclasses” of the ABCs. Those classes should define the full API including all of the abstract methods and all of the mixin methods. This lets users rely on issubclass() or isinstance() tests to determine whether the full interface is supported. The exception to this rule is for methods that are automatically inferred from the rest of the API:

 
 
 
 
  1. class D: # No inheritance
  2. def __init__(self): ... # Extra method not required by the ABC
  3. def __getitem__(self, index): ... # Abstract method
  4. def __len__(self): ... # Abstract method
  5. def count(self, value): ... # Mixin method
  6. def index(self, value): ... # Mixin method
  7. Sequence.register(D) # Register instead of inherit
 
 
 
 
  1. >>> issubclass(D, Sequence)
  2. True
  3. >>> isinstance(D(), Sequence)
  4. True

在這個例子中,D 類不需要定義 __contains__, __iter____reversed__ 因為 in 運算符, the 迭代 邏輯和 reversed() 函數(shù)會自動回退為使用 __getitem____len__。

3) Some simple interfaces are directly recognizable by the presence of the required methods (unless those methods have been set to None):

 
 
 
 
  1. class E:
  2. def __iter__(self): ...
  3. def __next__(next): ...
 
 
 
 
  1. >>> issubclass(E, Iterable)
  2. True
  3. >>> isinstance(E(), Iterable)
  4. True

復雜的接口不支持最后這種技術(shù)手段因為接口并不只是作為方法名稱存在。 接口指明了方法之間的語義和關(guān)系,這些是無法根據(jù)特定方法名稱的存在推斷出來的。 例如,知道一個類提供了 __getitem__, __len____iter__ 并不足以區(qū)分 Sequence 和 Mapping。

3.9 新版功能: 這些抽象類現(xiàn)在都支持 []。 參見 GenericAlias 類型 和 PEP 585。

容器抽象基類

這個容器模塊提供了以下 ABCs:

抽象基類

繼承自

抽象方法

Mixin 方法

Container 1

contains

Hashable 1

hash

Iterable 1 2

iter

Iterator 1

Iterable

next

iter

Reversible 1

Iterable

reversed

Generator 1

Iterator

send, throw

close, iter, next

Sized 1

len

Callable 1

call

Collection 1

Sized, Iterable, Container

contains, iter, len

Sequence

Reversible, Collection

getitem, len

contains, iter, reversed, index, and count

MutableSequence

Sequence

getitem, setitem, delitem, len, insert

繼承自 Sequence 的方法,以及 append, reverse, extend, pop, remove,和 iadd

ByteString

Sequence

getitem, len

繼承自 Sequence 的方法

Set

Collection

contains, iter, len

le, lt, eq, ne, gt, ge, and, or, sub, xor, and isdisjoint

MutableSet

Set

contains, iter, len, add, discard

繼承自 Set 的方法以及 clear, pop, remove, ior, iand, ixor,和 isub

Mapping

Collection

getitem, iter, len

contains, keys, items, values, get, eq, and ne

MutableMapping

Mapping

getitem, setitem, delitem, iter, len

繼承自 Mapping 的方法以及 pop, popitem, clear, update,和 setdefault

MappingView

Sized

len

ItemsView

MappingView, Set

contains, iter

KeysView

MappingView, Set

contains, iter

ValuesView

MappingView, Collection

contains, iter

Awaitable 1

await

Coroutine 1

Awaitable

send, throw

close

AsyncIterable 1

aiter

AsyncIterator 1

AsyncIterable

anext

aiter

AsyncGenerator 1

AsyncIterator

asend, athrow

aclose, aiter, anext

附注

1(1,2,3,4,5,6,7,8,9,10,11,12,13,14)

這些 ABC 重載了 object.__subclasshook__() 以便支持通過驗證所需的方法是否存在并且沒有被設(shè)為 None 來測試一個接口。 這只適用于簡單的接口。 更復雜的接口需要注冊或直接子類化。

2

檢查 isinstance(obj, Iterable) 是否偵測到被注冊為 Iterable 或者具有 __iter__() 方法的類,但它不能偵測到使用 __getitem__() 方法進行迭代的類。 確定一個對象是否為 iterable 的唯一可靠方式是調(diào)用 iter(obj)。

多項集抽象基類 — 詳細描述

class collections.abc.Container

提供了 __contains__() 方法的抽象基類。

class collections.abc.Hashable

提供了 __hash__() 方法的抽象基類。

class collections.abc.Sized

提供了 __len__() 方法的抽象基類。

class collections.abc.Callable

提供了 __call__() 方法的抽象基類。

class collections.abc.Iterable

提供了 __iter__() 方法的抽象基類。

使用 isinstance(obj, Iterable) 可以檢測一個類是否已經(jīng)注冊到了 Iterable 或者實現(xiàn)了 __iter__() 函數(shù),但是無法檢測這個類是否能夠使用 __getitem__() 方法進行迭代。檢測一個對象是否是 iterable 的唯一可信賴的方法是調(diào)用 iter(obj)

class collections.abc.Collection

集合了 Sized 和 Iterable 類的抽象基類。

3.6 新版功能.

class collections.abc.Iterator

提供了 __iter__() 和 __next__() 方法的抽象基類。參見 iterator 的定義。

class collections.abc.Reversible

為可迭代類提供了 __reversed__() 方法的抽象基類。

3.6 新版功能.

class collections.abc.Generator

生成器類,實現(xiàn)了 PEP 342 中定義的協(xié)議,繼承并擴展了迭代器,提供了 send(), throw() 和 close() 方法。參見 generator 的定義。

3.5 新版功能.

class collections.abc.Sequence

class collections.abc.MutableSequence

class collections.abc.ByteString

只讀的與可變的 序列 的抽象基類。

實現(xiàn)筆記:一些混入(Maxin)方法比如 __iter__(), __reversed__()index() 會重復調(diào)用底層的 __getitem__() 方法。因此,如果實現(xiàn)的 __getitem__() 是常數(shù)級訪問速度,那么相應(yīng)的混入方法會有一個線性的表現(xiàn);然而,如果底層方法是線性實現(xiàn)(例如鏈表),那么混入方法將會是平方級的表現(xiàn),這也許就需要被重構(gòu)了。

在 3.5 版更改: index() 方法支持 stopstart 參數(shù)。

class collections.abc.Set

class collections.abc.MutableSet

只讀的與可變的集合的抽象基類。

class collections.abc.Mapping

class collections.abc.MutableMapping

只讀的與可變的 映射 的抽象基類。

class collections.abc.MappingView

class collections.abc.ItemsView

class collections.abc.KeysView

class collections.abc.ValuesView

映射及其鍵和值的 視圖 的抽象基類。

class collections.abc.Awaitable

為可等待對象 awaitable 提供的類,可以被用于 await 表達式中。習慣上必須實現(xiàn) __await__() 方法。

協(xié)程 對象和 Coroutine ABC 的實例都是這個 ABC 的實例。

備注

In Cpython, generator-based coroutines (generators decorated with types.coroutine()) are awaitables, even though they do not have an __await__() method. Using isinstance(gencoro, Awaitable) for them will return False. Use inspect.isawaitable() to detect them.

3.5 新版功能.

class collections.abc.Coroutine

用于協(xié)程兼容類的抽象基類。實現(xiàn)了如下定義在 協(xié)程對象: 里的方法: send(),throw() 和 close()。通常的實現(xiàn)里還需要實現(xiàn) __await__() 方法。所有的 Coroutine 實例都必須是 Awaitable 實例。參見 coroutine 的定義。

備注

In CPython, generator-based coroutines (generators decorated with types.coroutine()) are awaitables, even though they do not have an __await__() method. Using isinstance(gencoro, Coroutine) for them will return False. Use inspect.isawaitable() to detect them.

3.5 新版功能.

class collections.abc.AsyncIterable

提供了 __aiter__ 方法的抽象基類。參見 asynchronous iterable 的定義。

3.5 新版功能.

class collections.abc.AsyncIterator

提供了 __aiter____anext__ 方法的抽象基類。參見 asynchronous iterator 的定義。

3.5 新版功能.

class collections.abc.AsyncGenerator

為異步生成器類提供的抽象基類,這些類實現(xiàn)了定義在 PEP 525 和 PEP 492 里的協(xié)議。

3.6 新版功能.

例子和配方

ABC 允許我們詢問類或?qū)嵗欠裉峁┨囟ǖ墓δ埽?

 
 
 
 
  1. size = None
  2. if isinstance(myvar, collections.abc.Sized):
  3. size = len(myvar)

有些抽象基類也可以用作混入類(mixin),這可以更容易地開發(fā)支持容器 API 的類。例如,要寫一個支持完整 Set API 的類,只需要提供下面這三個方法: __contains__(), __iter__()__len__()。抽象基類會補充上其余的方法,比如 __and__()isdisjoint():

 
 
 
 
  1. class ListBasedSet(collections.abc.Set):
  2. ''' Alternate set implementation favoring space over speed
  3. and not requiring the set elements to be hashable. '''
  4. def __init__(self, iterable):
  5. self.elements = lst = []
  6. for value in iterable:
  7. if value not in lst:
  8. lst.append(value)
  9. def __iter__(self):
  10. return iter(self.elements)
  11. def __contains__(self, value):
  12. return value in self.elements
  13. def __len__(self):
  14. return len(self.elements)
  15. s1 = ListBasedSet('abcdef')
  16. s2 = ListBasedSet('defghi')
  17. overlap = s1 & s2 # The __and__() method is supported automatically

當把 Set 和 MutableSet 用作混入類時需注意:

  1. 由于某些集合操作會創(chuàng)建新集合,默認的混入方法需要一種從可迭代對象里創(chuàng)建新實例的方式。 假定類構(gòu)造器具有 ClassName(iterable) 形式的簽名。 這樣它將執(zhí)行一個名為 _from_iterable() 的內(nèi)部類方法,該方法會調(diào)用 cls(iterable) 來產(chǎn)生一個新集合。 如果 Set 混入類在具有不同構(gòu)造器簽名的類中被使用,你將需要通過類方法或常規(guī)方法來重載 _from_iterable(),以便基于可迭代對象參數(shù)來構(gòu)造新的實例。

  2. 重載比較符時時(想必是為了速度,因為其語義都是固定的),只需要重定義 __le__()__ge__() 函數(shù),然后其他的操作會自動跟進。

  3. 混入集合類 Set 提供了一個 _hash() 方法為集合計算哈希值,然而, __hash__() 函數(shù)卻沒有被定義,因為并不是所有集合都是可哈希并且不可變的。為了使用混入類為集合添加哈希能力,可以同時繼承 Set() 和 Hashable() 類,然后定義 __hash__ = Set._hash

參見

  • OrderedSet recipe 是基于 MutableSet 構(gòu)建的一個示例。

  • 對于抽象基類,參見 abc 模塊和 PEP 3119。


網(wǎng)頁題目:創(chuàng)新互聯(lián)Python教程:collections.abc—-容器的抽象基類
網(wǎng)頁鏈接:http://www.dlmjj.cn/article/dhjeedo.html