【问题标题】:Creating class instance from dictionary?从字典创建类实例?
【发布时间】:2015-07-18 18:33:15
【问题描述】:

我正在尝试从具有键而不是类具有属性的字典创建类实例。我已经从这个链接阅读了相同问题的答案:Creating class instance properties from a dictionary?。问题是我不能在类定义中写__init__,因为我使用的是 SQLAlchemy 声明式样式类定义。此外,type('className', (object,), dict) 创建了不需要的错误属性。 这是我找到的解决方案:

dict = {'key1': 'value1', 'key2': 'value2'}
object = MyClass(**dict)

但如果 dict 有多余的键,它就不起作用:

dict = {'key1': 'value1', 'key2': 'value2', 'redundant_key': 'redundant_value'}
object = MyClass(**dict) # here need to ignore redundant_key

除了直接删除dict中的所有冗余键外,有什么解决办法吗?

【问题讨论】:

  • 什么是redundant_key
  • 你想如何为MyClass__init__?抱歉,我不熟悉 SQLAlchemy 声明式样式类定义。
  • @RafaelCardoso冗余键是存在于字典中但不存在于类属性中的键。
  • @PaulRooney __init__ 对于 MyClass,例如在这个答案中 stackoverflow.com/a/1639197/3700561
  • 那么您知道将输入哪些键吗?

标签: python class dictionary sqlalchemy


【解决方案1】:

使用classmethod 过滤字典并返回对象。

然后您不必强制您的 __init__ 方法接受字典。

import itertools

class MyClass(object):
    @classmethod
    def fromdict(cls, d):
        allowed = ('key1', 'key2')
        df = {k : v for k, v in d.iteritems() if k in allowed}
        return cls(**df)

    def __init__(self, key1, key2):
        self.key1 = key1
        self.key2 = key2

dict = {'key1': 'value1', 'key2': 'value2', 'redundant_key': 'redundant_value'}

ob = MyClass.fromdict(dict)

print ob.key1
print ob.key2

【讨论】:

    【解决方案2】:

    另一种解决方法是Filter dict to contain only certain keys:

    dict_you_want = { your_key: dict[your_key] for your_key in your_keys }
    

    【讨论】:

    • 然后在你的__init__函数中添加一行:self.__dict__.update(dict_you_want)
    【解决方案3】:

    对象的一个​​特殊的python魔术方法object.__dict__ “用于存储对象(可写)属性的字典或其他映射对象。” 因此,通过提升此功能...

    class MyClass(object):
       def __init__(self, **entries):
          self.__dict__.update(entries))
    
    dict = {'key1': 'value1', 'key2': 'value2', 'redundant_key': 'redundant_value'}
    
    ob = MyClass(**dict)
    

    注意:它不处理嵌套字典...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-10
      • 2021-12-07
      • 2020-10-22
      • 1970-01-01
      • 2014-03-03
      • 2017-02-05
      • 2020-07-30
      相关资源
      最近更新 更多