gpt4 book ai didi

python - 充当**解包映射的类

转载 作者:IT老高 更新时间:2023-10-28 20:23:07 28 4
gpt4 key购买 nike

如果没有子类化dict,一个类需要被认为是一个映射,以便它可以通过**传递给一个方法。

from abc import ABCMeta

class uobj:
__metaclass__ = ABCMeta

uobj.register(dict)

def f(**k): return k

o = uobj()
f(**o)

# outputs: f() argument after ** must be a mapping, not uobj

至少到了它会抛出缺少映射功能的错误,所以我可以开始实现。

我回顾了模拟容器类型,但简单地定义魔术方法没有效果,并且使用 ABCMeta 覆盖并将其注册为 dict 将断言验证为子类,但失败 isinstance(o, dict )。理想情况下,我什至不想使用 ABCMeta

最佳答案

__getitem__()keys() 方法就足够了:

>>> class D:
def keys(self):
return ['a', 'b']
def __getitem__(self, key):
return key.upper()


>>> def f(**kwds):
print kwds


>>> f(**D())
{'a': 'A', 'b': 'B'}

关于python - 充当**解包映射的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8601268/

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