python - 什么是 Python 映射?

标签 python syntax typeerror

假设我有一个函数 func 和一个属于 Class 类的对象 obj。我有以下错误:

>>> func(**obj)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: func() argument after ** must be a mapping, not Class

因此我的问题是:什么是映射?所有映射都是 dict 的子类吗?或者是否有 Class 必须实现的方法列表(例如 __getitem____iter__ ...)才能被视为映射?

最佳答案

描述了术语“映射”here作为:

A container object that supports arbitrary key lookups and implements the methods specified in the Mapping or MutableMapping abstract base classes. Examples include dict, collections.defaultdict, collections.OrderedDict and collections.Counter.

子类 collections.abc.Mapping 的要求在其文档字符串中描述:

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

This class provides concrete generic implementations of all
methods except for __getitem__, __iter__, and __len__.

"""

因此,您可以通过继承 collections.abc.Mapping 并实现三个方法来定义新的映射类型:__len____getitem____iter__

>>> from collections.abc import Mapping
>>> def func(**kwargs):
...   print(kwargs)
...
>>> class MyMapping(Mapping):
...   def __len__(self):
...     return 1
...   def __getitem__(self, k):
...     return 'bananas'
...   def __iter__(self):
...     return iter(['custard'])
...
>>> func(**MyMapping())
{'custard': 'bananas'}

关于python - 什么是 Python 映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56344997/

相关文章:

python - BeautifulSoup .find() 给出 TypeError

python - 正常列表 'type' 对象不可订阅

list - Python,匹配两个列表的元素

python - 将 xticks 和 yticks 放置在 imshow 图上的像素中心

python - 迭代地将第一列中的文本与其他列中的现有文本组合

python - 如何在 Python 中编写多行命令

scala - 在 Scala 中将 Option[T] 转换为 Option[U]

Mysql 触发器删除所有早于时间戳的行

python - TypeError:迭代 0-d 数组 Python

python - 如何使用一个 Firefox 实例 Selenium WebDriver 和 Python 运行多个测试?