Python从字典创建类实例 [英] Python creating class instance from dictionary

查看:809
本文介绍了Python从字典创建类实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从字典创建类实例,其中的键超过类的属性。我已经从此链接阅读了相同问题的答案:创建类Python中的字典的实例属性。问题是,我不能像我想要的那样在类定义中写 __ 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)#这里需要忽略redundant_key

除了直接从dict中删除所有冗余键,有没有其他解决方案?

解决方案

使用 classmethod 来过滤dict并返回对象。



然后,您不必强制您的 __ 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 )

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


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)

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

Are there any solutions except direct deleting all redundant keys from dict?

解决方案

Use a classmethod to filter the dict and return the object.

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

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