充当 ** 解包映射的类 [英] Class that acts as mapping for **unpacking

查看:33
本文介绍了充当 ** 解包映射的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果没有子类化 dict,类需要被视为映射以便可以将其传递给具有 ** 的方法.

from abc import ABCMetauobj 类:__元类__ = ABCMetauobj.register(字典)def f(**k): 返回 ko = uobj()f(**o)# 输出:** 之后的 f() 参数必须是映射,而不是 uobj

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

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

解决方案

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

<预><代码>>>>D类:定义键(自己):返回 ['a', 'b']def __getitem__(self, key):返回 key.upper()>>>def f(**kwds):打印 kwds>>>f(**D()){'a':'A','b':'B'}

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆