假设我有一个函数 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
orMutableMapping
abstract base classes. Examples includedict
,collections.defaultdict
,collections.OrderedDict
andcollections.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/