gpt4 book ai didi

python - 什么是 Python 映射?

转载 作者:行者123 更新时间:2023-11-28 20:30:53 24 4
gpt4 key购买 nike

假设我有一个函数 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/

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