python - 关键字参数解包要求

标签 python python-3.x python-2.7

在 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/

相关文章:

python - 可以利用类继承来使用 pytest 组织测试吗?

python - 使用Python 3安装Django 1.5时发生错误

python - django-filter如何向表单下的html标签添加属性

python - BaseSpider 和 CrawlSpider 的区别

python - replace() 函数没有替换 'e' 字符

python - 元素不再附加到 DOM 和超时异常

python - 转置后如何转置合并相同的列名?

python - torch 错误 : multi-target not supported in CrossEntropyLoss()

python - 如何在 Python/Tkinter 中使用浏览按钮显示文件路径

python - 如何使用类范围而不是类方法范围初始化/定义子类?