摘录来源 source:
- Data Model
- Book: Fluent Python 流畅的Python 前两章
Python 的特殊方法
表1-1:
跟运算符无关的特殊方法
Special method names (operators excluded)
类别 | Category | 方法名(Method names) |
---|---|---|
字符串 / 字节序列表示形式 | String/bytes representation | __repr__ __str__ __format__ __bytes__ |
数值转换 | Conversion to number | __abs__ __bool__ __complex__ __int__ __float__ __hash__ __index__ |
集合模拟 | Emulating collections | __len__ __getitem__ __setitem__ __delitem__ __contains__ |
迭代枚举 | Iteration | __iter__ __reversed__ __next__ |
可调用模拟 | Emulating callables | __call__ |
上下文管理 | Context management | __enter__ __exit__ |
实例创建和销毁 | Instance creation and destruction | __new__ __init__ __del__ |
属性管理 | Attribute management | __getattr__ __getattribute__ __setattr__ __delattr__ __dir__ |
属性描述符 | Attribute descriptors | __get__ __set__ __delete__ |
跟类相关的服务 | Class services | __prepare__ __instancecheck__ __subclasscheck__ |
表1-2:
跟运算符相关的特殊方法
Special method names for operators
类别 | Category | 方法名和对应的运算符(Method names and related operators) |
---|---|---|
一元运算符 | Unary numeric operators | __neg__ ← - __pos__ ← + __abs__ ← abs() |
众多比较运算符 | Rich comparison operators | __lt__ ← < __le__ ← <= __eq__ ← == __ne__ ← != __gt__ ← > __ge__ ← >= |
算术运算符 | Arithmetic operators | __add__ ← + __sub__ ← - __mul__ ← * __truediv__ ← / __floordiv__ ← // __mod__ ← % __divmod__ ← divmod() __pow__ ← ** __round__ ← round() |
反向算术运算符 | Reversed arithmetic operators | __radd__ __rsub__ __rmul__ __rtruediv__ __rfloordiv__ __rmod__ __rdivmod__ __rpow__ |
增量赋值算术运算符 | Augmented assignment arithmetic operators | __iadd__ __isub__ __imul__ __itruediv__ __ifloordiv__ __imod__ __ipow__ |
位运算符 | Bitwise operators | __invert__ ← ~ __lshift__ ← << __rshift__ ← >> __and__ ← & __or__ ← | __xor__ ← ^ |
反向位运算符 | Reversed bitwise operators | __rlshift__ __rrshift__ __rand__ __rxor__ __ror__ |
增量赋值位运算符 | ugmented assignment bitwise operators | __ilshift__ __irshift__ __iand__ __ixor__ __ior__ |
列表或元组或元组或双向队列的方法和属性
表2-1
列表或元组或元组或双向队列的方法和属性(那些由object类支持的方法没有列出来)
Methods and attributes found in list or tuple or array or deque (methods implemented by object are omitted for brevity)
列表 list | 元组 tuple | 数组 array | 双向队列 deque | ||
---|---|---|---|---|---|
s.__add__(s2) | ● | ● | ● | s + s2 → 拼接 concatenation | |
s.__iadd__(s2) | ● | ● | ● | s += s2 → 就地拼接 in-place concatenation | |
s.append(e) | ● | ● | ● | 在尾部添加一个新元素 Append one element after last | |
s.clear() | ● | ● | 删除所有元素 Delete all items | ||
s.__contains__(e) | ● | ● | ● | s 是否包含 e e in s | |
s.copy() | ● | 列表的浅复制 Shallow copy of the list | |||
s.count(e) | ● | ● | ● | ● | e 在 s 中出现的次数 Count occurrences of an element |
s.__delitem__(p) | ● | ● | ● | 把位于 p 的元素删除 Remove item at position p | |
s.extend(i) | ● | ● | ● | 将可迭代对象 i 中的元素添加到尾部 Append items from iterable i to the right | |
s.__getitem__(p) | ● | ● | ● | ● | s[p] → 获取位置 p 的元素 get item at position |
s.__getnewargs__() | ● | 在 pickle 中支持更加优化的序列化 Support for optimized serialization with pickle | |||
s.index(e) | ● | ● | ● | 在 s 中找到元素 e 第一次出现的位置 Find position of first occurrence of e | |
s.insert(p, e) | ● | ● | 在位置 p 之前插入元素e Insert element e before the item at position p | ||
s.__iter__() | ● | ● | ● | ● | 获取 s 的迭代器 Get iterator |
s.__len__() | ● | ● | ● | ● | len(s) → 元素的数量 number of items |
s.__mul__(n) | ● | ● | ● | s * n → n 个 s 的重复拼接 repeated concatenation | |
s.__imul__(n) | ● | ● | s *= n → 就地重复拼接 in-place repeated concatenation | ||
s.__rmul__(n) | ● | ● | ● | n * s → 反向拼接 * reversed repeated concatenationa | |
s.pop([p]) | ● | ● | 删除最后或者是(可选的)位于 p 的元素 → 并返回它的值 Remove and return last item or item at optional position p | ||
s.remove(e) | ● | ● | ● | 删除 s 中的第一次出现的 e Remove first occurrence of element e by value | |
s.reverse() | ● | ● | ● | 就地把 s 的元素倒序排列 Reverse the order of the items in place | |
s.__reversed__() | ● | ● | 返回 s 的倒序迭代器 Get iterator to scan items from last to first | ||
s.__setitem__(p, e) | ● | ● | ● | s[p] = e → 把元素 e 放在位置p 替代已经在那个位置的元素 put e in position p, overwriting existing item | |
s.sort([key], [reverse]) | ● | 就地对 s 中的元素进行排序 可选的参数有键(key)和是否倒序(reverse) Sort items in place with optional keyword arguments key and reverse | |||
s.byteswap() | ● | 翻转数组内每个元素的字节序列 转换字节序 Swap bytes of all items in array for endianess conversion | |||
s.__copy__() | ● | ● | 对 copy.copy 的支持 Support for copy.copy | ||
s.__deepcopy__() | ● | 对 copy.deepcopy 的支持 Optimized support for copy.deepcopy | |||
s.frombytes(b) | ● | 将压缩成机器值的字节序列读出来添加到尾部 Append items from byte sequence interpreted as packed machine values | |||
s.fromfile(f, n) | ● | 将二进制文件 f 内含有机器值读出来添加到尾部 最多添加 n 项 Append n items from binary file f interpreted as packed machine values | |||
s.fromlist(l) | ● | 将列表里的元素添加到尾部 如果其中任何一个元素导致了 TypeError 异常 那么所有的添加都会取消 Append items from list; if one causes TypeError, none are appended | |||
s.itemsize | ● | 数组中每个元素的长度是几个字节 Length in bytes of each array item | |||
s.tobytes() | ● | 把所有元素的机器值用 bytes 对象的形式返回 Return items as packed machine values in a bytes object | |||
s.tofile(f) | ● | 把所有元素以机器值的形式写入一个文件 Save items as packed machine values to binary file f | |||
s.tolist() | ● | 把数组转换成列表 列表里的元素类型是数字对象 Return items as numeric objects in a list | |||
s.typecode | ● | 返回只有一个字符的字符串 代表数组元素在 C 语言中的类型 One-character string identifying the C type of the items | |||
s.appendleft(e) | ● | 添加一个元素到最左侧(到第一个元素之前) Append one element to the left (before first) | |||
s.extendleft(i) | ● | 将可迭代对象 i 中的元素添加到头部 Append items from iterable i to the left | |||
s.pop() | ● | ● | 移除最后一个元素并返回它的值# Remove and return last itemb | ||
s.popleft() | ● | 移除第一个元素并返回它的值 Remove and return first item | |||
s.rotate(n) | ● | 把 n 个元素从队列的一端移到另一端 Move n items from one end to the other |
字典与集合的方法和属性
表3-1
dict、collections.defaultdict和collections.OrderedDict这三种映射类型的方法列表(依然省略了继承自object的常见方法);可选参数以[…]表示
Methods of the mapping types dict, collections.defaultdict, and collections. OrderedDict (common object methods omitted for brevity); optional arguments are enclosed in […]
dict | defaultdict | OrderedDict | ||
---|---|---|---|---|
d.clear() | ● | ● | ● | 移除所有元素 Remove all items |
d.__contains__(k) | ● | ● | ● | 检查 k 是否在 d 中 k in d |
d.copy() | ● | ● | ● | 浅复制 Shallow copy |
d.__copy__() | ● | 用于支持 copy.copy Support for copy.copy | ||
d.default_factory | ● | 在 __missing__ 函数中被调用的函数,用以给未找到的 元素设置值* Callable invoked by __missing__ to set missing valuesa | ||
d.__delitem__(k) | ● | ● | ● | del d[k] ,移除键为 k 的元素 del d[k] —remove item with key k |
d.fromkeys(it, [initial]) | ● | ● | ● | 将迭代器 it 里的元素设置为映射里的键,如果有 initial 参数,就把它作为这些键对应的值(默认是 None) New mapping from keys in iterable, with optional initial value (defaults to None) |
d.get(k, [default]) | ● | ● | ● | 返回键 k 对应的值,如果字典里没有键 k,则返回 None 或者 default Get item with key k, return default or None if missing |
d.__getitem__(k) | ● | ● | ● | 让字典 d 能用 d[k] 的形式返回键 k 对应的值 d[k] —get item with key k |
d.items() | ● | ● | ● | 返回 d 里所有的键值对 Get view over items (key, value) pairs |
d.__iter__() | ● | ● | ● | 获取键的迭代器 Get iterator over keys |
d.keys() | ● | ● | ● | 获取所有的键 Get view over keys |
d.__len__() | ● | ● | ● | 可以用 len(d) 的形式得到字典里键值对的数量 len(d) —number of items |
d.__missing__(k) | ● | 当 __getitem__ 找不到对应键的时候,这个方法会被调用 Called when __getitem__ cannot find the key | ||
d.move_to_end(k, [last]) | ● | 把键为 k 的元素移动到最靠前或者最靠后的位置(last 的默认值是 True) Move k first or last position (last is True by default) | ||
d.pop(k, [default]) | ● | ● | ● | 返回键 k 所对应的值,然后移除这个键值对。如果没有这个键,返回 None 或者 defaul Remove and return value at k, or default or None if missing |
d.popitem() | ● | ● | ● | 随机返回一个键值对并从字典里移除它# Remove and return an arbitrary (key, value) itemb |
d.__reversed__() | ● | 返回倒序的键的迭代器 Get iterator for keys from last to first inserted | ||
d.setdefault(k, [default]) | ● | ● | ● | 若字典里有键k,则把它对应的值设置为 default,然后返回这个值;若无,则让 d[k] = default ,然后返回 default If k in d, return d[k]; else set d[k] = default and return it |
d.__setitem__(k, v) | ● | ● | ● | 实现 d[k] = v 操作,把 k 对应的值设为 v put v at k |
d.update(m, [**kargs]) | ● | ● | ● | m 可以是映射或者键值对迭代器,用来更新 d 里对应的条目 Update d with items from mapping or iterable of (key, value) pairs |
d.values() | ● | ● | ● | 返回字典里的所有值 Get view over values |
表3-2
集合的数学运算:这些方法或者会生成新集合,或者会在条件允许的情况下就地修改集合
Mathematical set operations: these methods either produce a new set or update the target set in place, if it’s mutable
数学符号 Math_symbol | Python Python_operator | 运算符 Method | 方法描述 Description |
---|---|---|---|
S ∩ Z | s & z | s.__and__(z) | s 和 z 的交集 Intersection of s and z |
S ∩ Z | z & s | s.__rand__(z) | 反向 & 操作 Reversed & operator |
S ∩ Z | z & s | s.intersection(it, ...) | 把可迭代的 it 和其他所有参数转化为集合,然后求它们与 s 的交集 Intersection of s and all sets built from iterables it, etc. |
S ∩ Z | s &= z | s.__iand__(z) | 把 s 更新为 s 和 z 的交集 s updated with intersection of s and z |
S ∩ Z | s &= z | s.intersection_update(it, ...) | 把可迭代的 it 和其他所有参数转化为集合,然后求得它们与 s 的交集,然后把 s 更新成这个交集 s updated with intersection of s and all sets built from |
S ∪ Z | s | z | s.__or__(z) | s 和 z 的并集 Union of s and z |
S ∪ Z | z | s | s.__ror__(z) | | 的反向操作 Reversed | |
S ∪ Z | z | s | s.union(it, ...) | 把可迭代的 it 和其他所有参数转化为集合,然后求它们和 s 的并集 Union of s and all sets built from iterables it, etc. |
S ∪ Z | s |= z | s.__ior__(z) | 把 s 更新为 s 和 z 的并集 s updated with union of s and z |
S ∪ Z | s |= z | s.update(it, ...) | 把可迭代的 it 和其他所有参数转化为集合,然后求它们和 s 的并集,并把 s 更新成这个并集 s updated with union of s and all sets built from iterables it, etc. |
S \ Z | s - z | s.__sub__(z) | s 和 z 的差集,或者叫作相对补集 Relative complement or difference between s and z |
S \ Z | z - s | s.__rsub__(z) | s.__sub__(z) 的反向操作 Reversed - operator |
S \ Z | z - s | s.difference(it, ...) | 把可迭代的 it 和其他所有参数转化为集合,然后求它们和 s 的差集 Difference between s and all sets built from iterables it, etc. |
S \ Z | s -= z | s.__isub__(z) | 把 s 更新为它与 z 的差集 s updated with difference between s and z |
S \ Z | s -= z | s.difference_update(it, ...) | 把可迭代的 it 和其他所有参数转化为集合,求它们和 s 的差集,然后把 s 更新成这个差集 s updated with difference between s and all sets built from iterables it, etc. |
S \ Z | s -= z | s.symmetric_difference(it) | 求 s 和 set(it) 的对称差集 Complement of s & set(it) |
S △ Z | s ^ z | s.__xor__(z) | 求 s 和 z 的对称差集 Symmetric difference (the complement of the intersections & z) |
S △ Z | z ^ s | s.__rxor__(z) | ^ 的反向操作 Reversed ^ operator |
S △ Z | z ^ s | s.symmetric_difference_update(it,...) | 把可迭代的 it 和其他所有参数转化为集合,然后求它们和 s 的对称差集,最后把 s 更新成该结果 s updated with symmetric difference of s and all sets built from iterables it, etc. |
S △ Z | s ^= z | s.__ixor__(z) | 把 s 更新成它与 z 的对称差集 s updated with symmetric difference of s and z |
表3-3
集合的比较运算符,返回值是布尔类型
Set comparison operators and methods that return a bool
数学符号 Math_symbol | Python运算符 Python_operator | 方法 Method | 描述 Description |
---|---|---|---|
s.isdisjoint(z) | 查看 s 和 z 是否不相交(没有共同元素) s and z are disjoint (have no elements in common) | ||
e ∈ S | e in s | s.__contains__(e) | 元素 e 是否属于 s Element e is a member of s |
S ⊆ Z | s <= z | s.__le__(z) | 是否为 z 的子集 s is a subset of the z set |
S ⊆ Z | s <= z | s.issubset(it) | 把可迭代的 it 转化为集合,然后查看 s 是否为它的子集 s is a subset of the set built from the iterable it |
S ⊂ Z | s < z | s.__lt__(z) | s 是否为 z 的真子集 s is a proper subset of the z set |
S ⊇ Z | s >= z | s.__ge__(z) | s 是否为 z 的父集 s is a superset of the z set |
S ⊇ Z | s >= z | s.issuperset(it) | 把可迭代的 it 转化为集合,然后查看 s 是否为它的父集 s is a superset of the set built from the iterable it |
S ⊃ Z | s > z | s.__gt__(z) | s 是否为 z 的真父集 s is a proper superset of the z set |
表3-4
集合类型的其他方法
Additional set methods
set set | frozenset frozenset | ||
---|---|---|---|
s.add(e) | ● | 把元素 e 添加到 s 中 Add element e to s | |
s.clear() | ● | 移除掉 s 中的所有元素 Remove all elements of s | |
s.copy() | ● | ● | 对 s 浅复制 Shallow copy of s |
s.discard(e) | ● | 如果 s 里有 e 这个元素的话,把它移除 Remove element e from s if it is present | |
s.__iter__() | ● | ● | 返回 s 的迭代器 Get iterator over s |
s.__len__() | ● | ● | len(s) |
s.pop() | ● | 从 s 中移除一个元素并返回它的值,若 s 为空,则抛出 KeyError 异常 Remove and return an element from s, raising KeyError if s is empty | |
s.remove(e) | ● | 从 s 中移除 e 元素,若 e 元素不存在,则抛出 KeyError 异常 Remove element e from s, raising KeyError if e not in s |