Python从字典创建类实例 [英] Python creating class instance from dictionary
问题描述
我正在尝试从具有多个类的属性的键的字典创建类实例。我已经从以下链接中阅读了同一个问题的答案:创建课程Python中字典中的实例属性。问题是我不能像我想要的那样在类定义中写 __ init __
,因为我使用SQLAlchemy声明式样式类定义。另外 type('className',(object,),dict)
创建不需要的错误属性。
这是我找到的解决方案:
I am trying to create class instance from dictionary that has keys more than class has attributes. I already read answers on the same question from this link: Creating class instance properties from a dictionary in Python. The problem is that I can't write __init__
in class definition as I want, because I'm using SQLAlchemy declarative style class definition. Also type('className', (object,), dict)
creates wrong attributes that are not needed.
Here is the solution that I found:
dict = {'key1': 'value1', 'key2': 'value2'}
object = MyClass(**dict)
但它不如果dict有冗余密钥,则工作:
But it does not work if dict has redundant keys:
dict = {'key1': 'value1', 'key2': 'value2', 'redundant_key': 'redundant_value'}
object = MyClass(**dict) # here need to ignore redundant_key
是否有任何解决方案,除了直接从dict删除所有冗余密钥?
Are there any solutions except direct deleting all redundant keys from dict?
推荐答案
使用 classmethod
来过滤dict并返回对象。
Use a classmethod
to filter the dict and return the object.
然后,您不必强制您的 __ init __
方法接受dict。
You then dont have to force your __init__
method to accept a dict.
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
这篇关于Python从字典创建类实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!