充当 ** 解包映射的类 [英] Class that acts as mapping for **unpacking
问题描述
如果没有子类化 dict,类需要被视为映射以便可以将其传递给具有 **
的方法.
from abc import ABCMetauobj 类:__元类__ = ABCMetauobj.register(字典)def f(**k): 返回 ko = uobj()f(**o)# 输出:** 之后的 f() 参数必须是映射,而不是 uobj
至少到了它会抛出缺少映射功能的错误的程度,所以我可以开始实施.
我查看了模拟容器类型,但简单地定义魔术方法没有效果,并且使用 ABCMeta
覆盖并将其注册为 dict 将断言验证为子类,但失败 isinstance(o, dict)
.理想情况下,我什至不想使用 ABCMeta
.
__getitem__()
和 keys()
方法就足够了:
Without subclassing dict, what would a class need to be considered a mapping so that it can be passed to a method with **
.
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
At least to the point where it throws errors of missing functionality of mapping, so I can begin implementing.
I reviewed emulating container types but simply defining magic methods has no effect, and using ABCMeta
to override and register it as a dict validates assertions as subclass, but fails isinstance(o, dict)
. Ideally, I dont even want to use ABCMeta
.
The __getitem__()
and keys()
methods will suffice:
>>> 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'}
这篇关于充当 ** 解包映射的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!