sequences(序列) and mappings(映射)
sequence: 在python中,sequence指一些具有以下几种特性的数据类型的集合。
- 是可迭代对象。 可以用for...loop语句进行迭代。
- 有长度。 可以用len函数获得长度
- 可以通过整数下标访问里面的一个元素。
除了常见的list, tuple, string以外,range, bytes, bytearray等也都属于sequence。
所有sequence都要实现__getitem__和__len__方法,大部分还会实现__iter__方法。
collections.abc.Sequence提供了一个模板,用于实现自定义的sequence。
很多方法都实现了sequence.count(), sequence.index()方法。 继承collections.abc.Sequence这个抽象类时,就自动继承了这两个方法。
__contains__: 实现此方法可以实现item in obj语句功能。
__reversed__: 实现此方法,可以使用内置函数reversed函数对其进行倒序排列。
当我们明确自定义一个可变类型的sequence时,我们可以继承另一个抽象类collections.abc.MutableSequence
除了上述必须实现的__getitem__和__len__方法以外,为了实现可变sequence的功能,即可以对里面元素进行插入,修改和删除,则需要实现下面的方法。
__delitem__(): 可以使用del语句删除里面的元素
__setitem__(): 可以使用赋值语句修改元素值。
.insert(): 实现insert方法,在指定位置插入新元素。
还可以实现如下方法,以提供更丰富的元素遍历、访问、比较的功能。
.__contains__: Defines how to determine membership of the mapping.
.__eq__(): Defines how to determine equality of two objects.
.__ne__(): Defines how to determine when two objects are not equal.
.keys(): Defines how to access the keys in the mapping.
.values(): Defines how to access the values in the mapping.
.items(): Defines how to access the key-value pairs in the mapping.
.get(): Defines an alternative way to access values using keys. This method allows you to set a default value to use if the key isn’t present in the mapping.
collections.abc.MutableSequence抽象基类,我们就当成模板来继承,其还包括append, clear, reverse, extend, pop, remove,__iadd__ 这些方法,可以让我们实现这些常用的对元素的增加和移除的功能。
__iadd__(): 是用来实现+=操作符的。
mapping: 在python中,mapping指一些具有以下几种特性的键值对数据类型的集合。
- 是可迭代对象。 可以用for...loop语句进行迭代。
- 有长度。 可以用len函数获得长度
- 可以通过下标访问里面的一个元素。
collections.abc.Mapping提供了一个模板,用于实现自定义的mapping。
必须实现的三个特殊方法为: __getitem__(), __iter__(), __len__()。
要实现可修改的mapping, 可以继承collections.abc.MutableMapping抽象基类,此基类又多个两个必须实现的方法: __setitem__(), __delitem__()。
可以实现下面方法提供元素修改和删除功能。
.pop(): Defines how to remove a key from a mapping and return its value.
.popitem(): Defines how to remove and return the most recently added item in a mapping.
.clear(): Defines how to remove all the items from the mapping.
.update(): Defines how to update a dictionary using data passed as an argument to this method.
.setdefault(): Defines how to add a key with a default value if the key isn’t already in the mapping.

浙公网安备 33010602011771号