python – 根据dict类型,什么是映射对象?


class dict(**kwarg)
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)

这里的映射到底是什么? dict(映射)工作所需的最小接口是什么?

the source code for CPython开始,此评论:

/* We accept for the argument either a concrete dictionary object,
 * or an abstract "mapping" object.  For the former, we can do
 * things quite efficiently.  For the latter, we only require that
 * PyMapping_Keys() and PyObject_GetItem() be supported.

因此,“dict(映射)工作所需的最小接口”似乎是.keys()和.__ getitem __().


class M:
    def keys(self):
        return [1,2,3]
    def __getitem__(self, x):
        return x*2

m = M()

d = dict(m)

assert d == {1:2, 2:4, 3:6}

转载注明原文:python – 根据dict类型,什么是映射对象? - 代码日志