gpt4 book ai didi

python - 关键字参数解包要求

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

在 Python 中支持自定义类的关键字参数解包需要什么?在 Python 2.7 和 Python 3.6 解释器中,尝试解压缩不兼容的类型时会给出以下错误消息:

>>> dict(**None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: type object argument after ** must be a mapping, not NoneType

mapping 是否意味着对象必须专门子类化 collections.Mapping?或者在这种情况下,mapping 是那些伪类型之一,例如 iterable,您不必显式子类化 collections.Iterable 来支持 迭代器()?这种行为在 Python 2 和 3 之间是否不同?

最佳答案

A Mapping is a generic container for associating key/value pairs.

为了使用字典解包,不必继承collections.Mapping。此外,collections.Mapping 是一个抽象类,因此您仍然需要重写一些方法,以便能够对其任何子类使用 dict 解包。

要使类的实例dict unpackable,该类实现一个keys 方法和相应的__getitem__ 就足够了给定键返回值的方法:

class D(object):
def __getitem__(self, key):
return 2

def keys(self):
return ['1','2','3']

print(dict(**D()))
# {'1': 2, '2': 2, '3': 2}

关于python - 关键字参数解包要求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47340671/

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