Python - 额外的关键字(?)和继承

luk*_*keg 5 python python-3.x

typing.py(从与 Anaconda 捆绑在一起的 Python 3.6.6 开始)声明List类如下:

class List(list, MutableSequence[T], extra=list):

据我的理解,这意味着List类继承自listMutableSequence[T])。extra继承列表中的赋值是什么意思?

Pri*_*usa 5

typing.py类中GenericMeta采用extra关键字参数。这个extra论点只是内部簿记所需要的论点之一GenericMeta。更新发生__new__GenericMeta

namespace.update({'__origin__': origin, '__extra__': extra,
                      '_gorg': None if not origin else origin._gorg})
Run Code Online (Sandbox Code Playgroud)

从此时起,cls.__extra__成为 的内部 API 的一部分Typing,很像__getattr____len__。从源代码来看,它似乎__extra__用于帮助设置传入的类的属性:

def __init__(self, *args, **kwargs):
    super(GenericMeta, self).__init__(*args, **kwargs)
    if isinstance(self.__extra__, abc.ABCMeta):
        self._abc_registry = self.__extra__._abc_registry
        self._abc_cache = self.__extra__._abc_cache
    elif self.__origin__ is not None:
        self._abc_registry = self.__origin__._abc_registry
        self._abc_cache = self.__origin__._abc_cache
Run Code Online (Sandbox Code Playgroud)

该代码用于__extra__设置_abc_registry_abc_cache