python: collections
Ordereddict
把 這個和 sorted 使用的栗子 也順便看了!
class collections.abc.MutableMapping
繼承類必須實現的 Abstract Methods 有:
__getitem__, __setitem__, __delitem__, __iter__, __len__
原始碼實現 Lib/collections.abc
class MutableMapping(Mapping):
__slots__ = ()
"""A MutableMapping is a generic container for associating
key/value pairs.
This class provides concrete generic implementations of all
methods except for __getitem__, __setitem__, __delitem__,
__iter__, and __len__.
"""
@abstractmethod
def __setitem__(self, key, value):
raise KeyError
@abstractmethod
def __delitem__(self, key):
raise KeyError
__marker = object()
def pop(self, key, default=__marker):
'''D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised.
'''
try:
value = self[key]
except KeyError:
if default is self.__marker:
raise
return default
else:
del self[key]
return value
def popitem(self):
'''D.popitem() -> (k, v), remove and return some (key, value) pair
as a 2-tuple; but raise KeyError if D is empty.
'''
try:
key = next(iter(self))
except StopIteration:
raise KeyError
value = self[key]
del self[key]
return key, value
def clear(self):
'D.clear() -> None. Remove all items from D.'
try:
while True:
self.popitem()
except KeyError:
pass
def update(*args, **kwds):
''' D.update([E, ]**F) -> None. Update D from mapping/iterable E and F.
If E present and has a .keys() method, does: for k in E: D[k] = E[k]
If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v
In either case, this is followed by: for k, v in F.items(): D[k] = v
'''
if not args:
raise TypeError("descriptor 'update' of 'MutableMapping' object "
"needs an argument")
self, *args = args
if len(args) > 1:
raise TypeError('update expected at most 1 arguments, got %d' %
len(args))
if args:
other = args[0]
if isinstance(other, Mapping):
for key in other:
self[key] = other[key]
elif hasattr(other, "keys"):
for key in other.keys():
self[key] = other[key]
else:
for key, value in other:
self[key] = value
for key, value in kwds.items():
self[key] = value
def setdefault(self, key, default=None):
'D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D'
try:
return self[key]
except KeyError:
self[key] = default
return default
MutableMapping.register(dict)
對應父類 Mapping 的原始碼
class Mapping(Collection):
__slots__ = ()
"""A Mapping is a generic container for associating key/value
pairs.
This class provides concrete generic implementations of all
methods except for __getitem__, __iter__, and __len__.
"""
@abstractmethod
def __getitem__(self, key):
raise KeyError
def get(self, key, default=None):
'D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.'
try:
return self[key]
except KeyError:
return default
def __contains__(self, key):
try:
self[key]
except KeyError:
return False
else:
return True
def keys(self):
"D.keys() -> a set-like object providing a view on D's keys"
return KeysView(self)
def items(self):
"D.items() -> a set-like object providing a view on D's items"
return ItemsView(self)
def values(self):
"D.values() -> an object providing a view on D's values"
return ValuesView(self)
def __eq__(self, other):
if not isinstance(other, Mapping):
return NotImplemented
return dict(self.items()) == dict(other.items())
__reversed__ = None
Mapping.register(mappingproxy)
接著看看 KeysView
class KeysView(MappingView, Set):
__slots__ = ()
@classmethod
def _from_iterable(self, it):
return set(it)
def __contains__(self, key):
return key in self._mapping
def __iter__(self):
yield from self._mapping
KeysView.register(dict_keys)
再看看 MappingView
class MappingView(Sized):
__slots__ = '_mapping',
def __init__(self, mapping):
self._mapping = mapping
def __len__(self):
return len(self._mapping)
def __repr__(self):
return '{0.__class__.__name__}({0._mapping!r})'.format(self)
參考
python documentation: collections.abc
python documentation: collections
相關文章
- python collections模組Python
- Python 的 collections模組Python
- python模組之collections模組Python
- Python collections 模組筆記Python筆記
- Go 實現的 python collectionsGoPython
- python—collections模組(defaultdict、Counter、OrderedDict)Python
- Python中Collections.counter用法Python
- Python中的collections.Counter模組Python
- 不可不知的python模組–collectionsPython
- python中collections.Counter是什麼?Python
- collections模組
- java collectionsJava
- Python原生資料結構增強模組collectionsPython資料結構
- Python collections.defaultdict() 與 dict的使用和區別Python
- Collections工具類
- 集合框架-Collections框架
- RobotFramework之CollectionsFramework
- Collections in Swift 4Swift
- Collections sort()排序方法排序
- 6、Collections工具類
- 淺談 Laravel CollectionsLaravel
- Collections排序問題!!排序
- 每日一模組-collections
- Python基礎系列講解——內建庫之collections的使用Python
- Java 集合類——Collections(1)Java
- Java 集合類——Collections(3)Java
- Java 集合類——Collections(2)Java
- 7、Collections集合工具類
- Java之Collections工具類Java
- 【java】【Map】HashMap、Hashtable、CollectionsJavaHashMap
- Java Collections 原始碼分析Java原始碼
- 橫掃Java Collections系列 —— TreeSetJava
- Debugging collections(譯)
- Collections.sort()方法,字元排序字元排序
- 橫掃Java Collections系列 —— ListJava
- Java —— 集合工具類(Collections 類)Java
- collection和collections的區別
- JavaSE基礎:Collections工具類Java