【发布时间】: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