【问题标题】:Comprehensive list of Python protocols/interfacesPython 协议/接口的综合列表
【发布时间】:2011-08-30 13:43:56
【问题描述】:

最近,我在看一些 Python 习语。 我发现了许多 Python 中使用的协议的描述,例如排序 (__cmp__, ...) 或生成器。此外,还有像__hash__ 这样为每个对象定义的方法(我想)。

在互联网上进行了一些搜索后,我没有找到这些协议和方法的完整列表。 谁能给我一些 pointers 网址?

【问题讨论】:

标签: python interface protocols


【解决方案1】:

按照惯例,协议是一组描述常见行为的特殊方法。您可以从 collections.abc 模块 (Python 3.3+) 的抽象方法中推断协议;另见docs。使用以下内容自动列出此列表:

给定

import abc

import collections as ct

代码

def get_protocols(source=ct.abc):
    """Return a dict of protocols from `collections.abc`."""
    d = {}

    for objname in dir(source):

        if objname.startswith("_"):
            continue
        obj = getattr(source, objname)
        abmethods = sorted(obj.__abstractmethods__)
        if not abmethods:
            continue    
        d[objname] = abmethods        
    return d

演示

get_protocols()

输出

{
 'AsyncGenerator': ['asend', 'athrow'], 
 'AsyncIterable': ['__aiter__'], 
 'AsyncIterator': ['__anext__'],
 'Awaitable': ['__await__'], 
 'ByteString': ['__getitem__', '__len__'],
 'Callable': ['__call__'], 
 'Collection': ['__contains__', '__iter__', '__len__'], 
 'Container': ['__contains__'], 
 'Coroutine': ['__await__', 'send', 'throw'], 
 'Generator': ['send', 'throw'], 
 'Hashable': ['__hash__'], 
 'Iterable': ['__iter__'], 
 'Iterator': ['__next__'],
 'Mapping': ['__getitem__', '__iter__', '__len__'], 
 'MutableMapping': ['__delitem__', '__getitem__', '__iter__', '__len__', '__setitem__'],
 'MutableSequence': ['__delitem__', '__getitem__', '__len__', '__setitem__', 'insert'], 
 'MutableSet': ['__contains__', '__iter__', '__len__', 'add', 'discard'],
 'Reversible': ['__iter__', '__reversed__'], 
 'Sequence': ['__getitem__', '__len__'], 
 'Set': ['__contains__', '__iter__', '__len__'], 
 'Sized': ['__len__']
}

注意:子类化时,这些是(必需的)抽象方法,不包括 mixin 方法。示例:子类化collections.abc.Mappings 将在协议实现后提供方法.keys().values().items()(未列出)。

【讨论】:

    【解决方案2】:

    您最好的参考永远是Python Online Documentation,特别是Special method names 部分。

    交互式 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)
    

    【讨论】:

      猜你喜欢
      • 2021-07-17
      • 1970-01-01
      • 1970-01-01
      • 2018-02-10
      • 1970-01-01
      • 1970-01-01
      • 2011-01-28
      • 1970-01-01
      • 2012-11-14
      相关资源
      最近更新 更多