- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我在学习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 bydict.__getitem__()
to implementself[key]
for dict subclasses when key is not in the dictionary.
比之前的示例代码还要困难。这里也有很好的答案。
最后一个答案获得了 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/
我在学习str.format_map()时遇到了一个“类”的例子(Python String format_map()) class Coordinate(dict): def __missi
我已经在自己的机器上“玩”git 6 个月了,我真的很喜欢它。 但是,我发现很难真正理解如何在团队/企业环境中使用它。 (我想知道 Eric Sink 是否正确)。 我开始尝试在 Windows 上安
我是一名优秀的程序员,十分优秀!