gpt4 book ai didi

python - 摸索 `__missing__`

转载 作者:太空宇宙 更新时间:2023-11-03 14:33:11 24 4
gpt4 key购买 nike

我在学习str.format_map()时遇到了一个“类”的例子(Python String format_map())

class Coordinate(dict):
def __missing__(self, key):
return key

尝试参数:

In [25]: Coordinate(x='6')
Out[25]: {'x': '6'}

In [26]: Coordinate(x='6', y='7')
Out[26]: {'x': '6', 'y': '7'}

最难理解的是,x=6 既不是 dict,也不是 {'x': '6'} key .

在官方文档中,它指定:

object.__missing__(self, key)Called by dict.__getitem__() to implement self[key] for dict subclasses when key is not in the dictionary.

比之前的示例代码还要困难。这里也有很好的答案。

dictionary - Python 2 missing method - Stack Overflow

Hidden features of Python - Stack Overflow

最后一个答案获得了 258 票赞成,这让我非常沮丧,因为我对此一无所知。有Python基础知识就能理解吗?

最佳答案

这里与__missing__无关:

>>> Coordinate(x='6')
{'x': '6'}
>>> dict(x='6')
{'x': '6'}

这只是调用 dict 初始值设定项,因为您继承了 dict 并且没有覆盖 __init__

定义__missing__的效果如下所示:

>>> c = Coordinate(x='6')
>>> c['new_key']
'new_key' # returns the key, instead of raising KeyError
>>> c # note: does not set it in the dict
{'x': '6'}

关于python - 摸索 `__missing__`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47140570/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com