Python协议/接口综合列表
最近,我在研究一些Python的用法。发现了很多关于Python中使用的协议的描述,比如排序(__cmp__
等)或者生成器。此外,还有像__hash__
这样的函数,似乎是为每个对象都定义的。
我在网上搜索了一下,没找到一个全面的这些协议和方法的列表。有没有人能给我一些相关的网址?
2 个回答
10
更新:这个函数现在会遍历一个对象的子类链,并提取所有的抽象方法。如果你想使用之前的行为,可以设置 nested=False
。
按照惯例,协议是一组特殊的方法,用来描述一些共同的行为。你可以从 collections.abc
模块中的抽象方法大致推测出这些协议(适用于Python 3.3及以上版本);更多信息可以查看 文档。你可以用以下方法自动列出这些协议:
给定
import abc
import collections as ct
代码
def get_protocols(source=ct.abc, nested=True):
"""Return a dict of protocols from source abstractmethods only."""
dd = ct.defaultdict(set)
for objname in dir(source):
if objname.startswith("_"):
continue
obj = getattr(source, objname)
classes = obj.__mro__ if nested else [obj]
for cls in classes:
if cls is object:
continue
abmethods = sorted(cls.__abstractmethods__)
if not abmethods:
continue
dd[objname] |= set(abmethods)
return dict(dd)
演示
get_protocols()
输出
{
'AsyncGenerator': {'__aiter__', '__anext__', 'asend', 'athrow'},
'AsyncIterable': {'__aiter__'},
'AsyncIterator': {'__aiter__', '__anext__'},
'Awaitable': {'__await__'},
'ByteString': {'__contains__', '__getitem__', '__iter__', '__len__', '__reversed__'},
'Callable': {'__call__'},
'Collection': {'__contains__', '__iter__', '__len__'},
'Container': {'__contains__'},
'Coroutine': {'__await__', 'send', 'throw'},
'Generator': {'__iter__', '__next__', 'send', 'throw'},
'Hashable': {'__hash__'},
'ItemsView': {'__contains__', '__iter__', '__len__'},
'Iterable': {'__iter__'},
'Iterator': {'__iter__', '__next__'},
'KeysView': {'__contains__', '__iter__', '__len__'},
'Mapping': {'__contains__', '__getitem__', '__iter__', '__len__'},
'MappingView': {'__len__'},
'MutableMapping': {'__contains__', '__delitem__', '__getitem__', '__iter__', '__len__', '__setitem__'},
'MutableSequence': {'__contains__', '__delitem__', '__getitem__', '__iter__', '__len__', '__reversed__', '__setitem__', 'insert'},
'MutableSet': {'__contains__', '__iter__', '__len__', 'add', 'discard'},
'Reversible': {'__iter__', '__reversed__'},
'Sequence': {'__contains__', '__getitem__', '__iter__', '__len__', '__reversed__'},
'Set': {'__contains__', '__iter__', '__len__'},
'Sized': {'__len__'},
'ValuesView': {'__contains__', '__iter__', '__len__'}
}
注意:在子类化时,这些是(必需的)抽象方法,不包括混入方法。例如:子类化 collections.abc.Mappings
将提供方法 .keys()
、.values()
、.items()
(未列出),一旦实现了协议。
注意:这里只列出了抽象方法。一些方法被排除在外,例如所有生成器类函数中的 close()
方法。
16
你最好的参考资料永远是Python在线文档,特别是关于特殊方法名称的部分。
交互式的Python解释器也是一个非常有用的工具。你可以试试下面这些:
>>> dir(object)
['__class__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
>>> help(object.__class__)
>>> help(object.__hash__)
>>> help(hash)