从字典创建类实例? [英] Creating class instance from dictionary?

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

问题描述

我试图从字典创建类实例,该类实例具有比类具有属性更多的键.我已经通过以下链接阅读了有关同一问题的答案:通过字典?.问题是我无法根据需要在类定义中编写__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?. 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过滤字典并返回对象.

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

然后,您不必强制您的__init__方法接受命令.

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

这篇关于从字典创建类实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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