什么是映射对象,根据dict类型? [英] What is a mapping object, according to dict type?

查看:117
本文介绍了什么是映射对象,根据dict类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文档列出了创建dict实例的3种方法:

The documentation lists 3 ways for creating a dict instance:

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

这里是一个映射究竟是什么? dict(mapping)要工作的最小接口是什么?

What exactly is a mapping here? What's the minimal interface required for dict(mapping) to work?

推荐答案

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 __()

So, "the minimal interface required for dict(mapping) to work" appears to be .keys() and .__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}

这篇关于什么是映射对象,根据dict类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆