collections.abc
— 컨테이너의 추상 베이스 클래스¶
Added in version 3.3: 이전에는, 이 모듈이 collections
모듈의 일부였습니다.
소스 코드: Lib/_collections_abc.py
이 모듈은 클래스가 특정 인터페이스를 제공하는지를 검사하는 데 사용할 수 있는 추상 베이스 클래스를 제공합니다; 예를 들어, 해시 가능인지 또는 매핑인지입니다.
An issubclass()
or isinstance()
test for an interface works in one
of three ways.
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:
class C(Sequence): # 직접 상속 def __init__(self): ... # ABC 가 요구하지 않는 추가 메서드 def __getitem__(self, index): ... # 필수 추상 메서드 def __len__(self): ... # 필수 추상 메서드 def count(self, value): ... # 선택적으로 믹스인 메서드를 재정의합니다
>>> issubclass(C, Sequence) True >>> isinstance(C(), Sequence) True
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()
orisinstance()
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:class D: # 상속 없음 def __init__(self): ... # ABC 가 요구하지 않는 추가 메서드 def __getitem__(self, index): ... # 추상 메서드 def __len__(self): ... # 추상 메서드 def count(self, value): ... # 믹스인 메서드 def index(self, value): ... # 믹스인 메서드 Sequence.register(D) # 상속하는 대신 등록합니다
>>> issubclass(D, Sequence) True >>> isinstance(D(), Sequence) True
In this example, class
D
does not need to define__contains__
,__iter__
, and__reversed__
because the in-operator, the iteration logic, and thereversed()
function automatically fall back to using__getitem__
and__len__
.Some simple interfaces are directly recognizable by the presence of the required methods (unless those methods have been set to
None
):class E: def __iter__(self): ... def __next__(self): ...
>>> issubclass(E, Iterable) True >>> isinstance(E(), Iterable) True
Complex interfaces do not support this last technique because an interface is more than just the presence of method names. Interfaces specify semantics and relationships between methods that cannot be inferred solely from the presence of specific method names. For example, knowing that a class supplies
__getitem__
,__len__
, and__iter__
is insufficient for distinguishing aSequence
from aMapping
.
Added in version 3.9: These abstract classes now support []
. See 제네릭 에일리어스 형
and PEP 585.
Collections 추상 베이스 클래스¶
collections 모듈은 다음과 같은 ABC를 제공합니다:
ABC |
상속 |
추상 메서드 |
믹스인 메서드 |
---|---|---|---|
|
|||
|
|||
|
|||
|
|
||
|
|||
|
|
||
|
|||
|
|||
|
|||
|
|
||
|
상속된 |
||
|
상속된 |
||
|
|
||
|
상속된 |
||
|
|
||
|
상속된 |
||
|
|||
|
|||
|
|||
|
|||
|
|||
|
|
||
|
|||
|
|
||
|
|
||
|
각주
Collections 추상 베이스 클래스 – 상세한 설명¶
- class collections.abc.Container¶
__contains__()
메서드를 제공하는 클래스의 ABC.
- class collections.abc.Hashable¶
__hash__()
메서드를 제공하는 클래스의 ABC.
- class collections.abc.Callable¶
__call__()
메서드를 제공하는 클래스의 ABC.See Annotating callable objects for details on how to use
Callable
in type annotations.
- class collections.abc.Iterable¶
__iter__()
메서드를 제공하는 클래스의 ABC.isinstance(obj, Iterable)
를 검사하면Iterable
로 등록되었거나__iter__()
메서드가 있는 클래스를 감지하지만,__getitem__()
메서드로 이터레이트 하는 클래스는 감지하지 않습니다. 객체가 이터러블인지를 확인하는 유일하게 신뢰성 있는 방법은iter(obj)
를 호출하는 것입니다.
- class collections.abc.Collection¶
길이가 있는 이터러블 컨테이너 클래스의 ABC.
Added in version 3.6.
- class collections.abc.Iterator¶
__iter__()
와__next__()
메서드를 제공하는 클래스의 ABC. 이터레이터의 정의도 참조하십시오.
- class collections.abc.Reversible¶
__reversed__()
메서드도 제공하는 이터러블 클래스의 ABC.Added in version 3.6.
- class collections.abc.Generator¶
send()
,throw()
및close()
메서드로 이터레이터를 확장하는 PEP 342에 정의된 프로토콜을 구현하는 제너레이터 클래스의 ABC.See Annotating generators and coroutines for details on using
Generator
in type annotations.Added in version 3.5.
- class collections.abc.Sequence¶
- class collections.abc.MutableSequence¶
- class collections.abc.ByteString¶
읽기 전용과 가변 시퀀스의 ABC.
구현 참고 사항:
__iter__()
,__reversed__()
및index()
와 같은 일부 믹스인(mixin) 메서드는 하부__getitem__()
메서드를 반복적으로 호출합니다. 따라서,__getitem__()
이 상수 액세스 속도로 구현되면 믹스인 메서드는 선형 성능을 갖습니다; 그러나 하부 메서드가 선형이면 (링크드 리스트에서처럼), 믹스인은 2차 함수 성능을 가지므로 재정의해야 할 수 있습니다.버전 3.5에서 변경: index() 메서드는 stop과 start 인자에 대한 지원을 추가했습니다.
Deprecated since version 3.12, will be removed in version 3.14: The
ByteString
ABC has been deprecated. For use in typing, prefer a union, likebytes | bytearray
, orcollections.abc.Buffer
. For use as an ABC, preferSequence
orcollections.abc.Buffer
.
- class collections.abc.MappingView¶
- class collections.abc.ItemsView¶
- class collections.abc.KeysView¶
- class collections.abc.ValuesView¶
매핑, 항목, 키 및 값 뷰의 ABC.
- class collections.abc.Awaitable¶
await
표현식에서 사용할 수 있는 어웨이터블 객체의 ABC. 사용자 정의 구현은__await__()
메서드를 제공해야 합니다.코루틴 객체와
Coroutine
ABC의 인스턴스는 모두 이 ABC의 인스턴스입니다.참고
CPython에서, 제너레이터 기반 코루틴(
@types.coroutine
으로 데코레이트 된 제너레이터)은,__await__()
메서드가 없어도 어웨이터블 입니다. 이들에 대해isinstance(gencoro, Awaitable)
를 사용하면False
가 반환됩니다. 이들을 감지하려면inspect.isawaitable()
을 사용하십시오.Added in version 3.5.
- class collections.abc.Coroutine¶
코루틴 호환 클래스의 ABC. 코루틴 객체(Coroutine Objects)에 정의된 다음 메서드를 구현합니다:
send()
,throw()
및close()
. 사용자 정의 구현은__await__()
도 구현해야 합니다. 모든Coroutine
인스턴스는Awaitable
의 인스턴스이기도 합니다.참고
CPython에서, 제너레이터 기반 코루틴(
@types.coroutine
으로 데코레이트 된 제너레이터)은,__await__()
메서드가 없어도 어웨이터블 입니다. 이들에 대해isinstance(gencoro, Coroutine)
을 사용하면False
가 반환됩니다. 이들을 감지하려면inspect.isawaitable()
을 사용하십시오.See Annotating generators and coroutines for details on using
Coroutine
in type annotations. The variance and order of type parameters correspond to those ofGenerator
.Added in version 3.5.
- class collections.abc.AsyncIterable¶
__aiter__
메서드를 제공하는 클래스의 ABC. 비동기 이터러블의 정의도 참조하십시오.Added in version 3.5.
- class collections.abc.AsyncIterator¶
__aiter__
와__anext__
메서드를 제공하는 클래스의 ABC. 비동기 이터레이터의 정의도 참조하십시오.Added in version 3.5.
- class collections.abc.AsyncGenerator¶
PEP 525와 PEP 492에 정의된 프로토콜을 구현하는 비동기 제너레이터 클래스의 ABC.
See Annotating generators and coroutines for details on using
AsyncGenerator
in type annotations.Added in version 3.6.
- class collections.abc.Buffer¶
ABC for classes that provide the
__buffer__()
method, implementing the buffer protocol. See PEP 688.Added in version 3.12.
예제와 조리법¶
ABC들은 클래스나 인스턴스가 특정 기능을 제공하는지 묻는 것을 허용합니다, 예를 들어:
size = None
if isinstance(myvar, collections.abc.Sized):
size = len(myvar)
ABC 중 일부는 믹스인으로도 유용하여 컨테이너 API를 지원하는 클래스를 쉽게 개발할 수 있게 합니다. 예를 들어, 전체 Set
API를 지원하는 클래스를 작성하려면, __contains__()
, __iter__()
및 __len__()
의 세 가지 하부 추상 메서드 만 제공하면 됩니다. ABC는 __and__()
와 isdisjoint()
와 같은 나머지 메서드를 제공합니다:
class ListBasedSet(collections.abc.Set):
''' 속도보다 공간을 선호하고 집합 원소가
해시 가능할 필요가 없는 대안 집합 구현. '''
def __init__(self, iterable):
self.elements = lst = []
for value in iterable:
if value not in lst:
lst.append(value)
def __iter__(self):
return iter(self.elements)
def __contains__(self, value):
return value in self.elements
def __len__(self):
return len(self.elements)
s1 = ListBasedSet('abcdef')
s2 = ListBasedSet('defghi')
overlap = s1 & s2 # __and__() 메서드는 자동으로 지원됩니다
Set
과 MutableSet
을 믹스인으로 사용할 때의 주의 사항:
일부 집합 연산은 새로운 집합을 만들기 때문에, 기본 믹스인 메서드는 이터러블로부터 새 인스턴스를 만드는 방법이 필요합니다. 클래스 생성자가
ClassName(iterable)
형식의 서명을 가진 것으로 가정합니다. 이 가정은 새로운 집합을 생성하기 위해cls(iterable)
를 호출하는_from_iterable()
이라는 내부classmethod
로 분리되었습니다.Set
믹스인이 다른 생성자 서명을 갖는 클래스에서 사용되고 있으면, 이터러블 인자로부터 새 인스턴스를 생성할 수 있는 클래스 메서드나 일반 메서드로_from_iterable()
을 재정의해야 합니다.비교를 재정의하려면 (의미는 고정되었으므로, 아마도 속도 때문에),
__le__()
와__ge__()
를 재정의하십시오, 그러면 다른 연산은 자동으로 맞춰집니다.Set
믹스인은 집합의 해시값을 계산하는_hash()
메서드를 제공합니다; 그러나 모든 집합이 해시 가능하거나 불변이지는 않기 때문에__hash__()
는 정의되지 않습니다. 믹스인을 사용하여 집합 해시 가능성을 추가하려면,Set()
와Hashable()
을 모두 상속한 다음,__hash__ = Set._hash
를 정의하십시오.
더 보기
MutableSet
으로 구축한 예제 OrderedSet 조리법.