简体   繁体   English

输出** kwargs,* args的__dict__类

[英]class __dict__ from output **kwargs, *args

I am trying to make a class that will make a dict using __dict__ out of 我正在尝试创建一个将使用__dict__做出命令的类

attrdict(name = ("American","bbbb"),weight=(2,2.5))

I trying to start with 我开始尝试

class attrdict(dict):
    def __init__(self, *args, **kwargs):
        dict.__init__(self, *args, **kwargs)
        self.__dict__ = self

This returns {'name': ('American', 'bbbb'), 'weight': (2, 2.5)} , but I need it in a way I can call "American" and it will return 2. 这将返回{'name': ('American', 'bbbb'), 'weight': (2, 2.5)} ,但是我需要一种可以称为“ American”的方式,它将返回2。

I am stuck. 我被困住了。 Can someone please point me in the right direction. 有人能指出我正确的方向吗?

If you want such result then pass the zipped values: 如果您想要这样的结果,则传递压缩值:

class attrdict(dict):
    def __init__(self, *args, **kwargs):
        dict.__init__(self, dict(*args))
        self.__dict__ = self

Demo: 演示:

>>> d = attrdict(zip(("American","bbbb"),(2,2.5)))
>>> d['American']
2
>>> d['bbbb']
2.5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM