在Python中从字典中创建类实例属性 [英] Creating class instance properties from a dictionary in Python

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

问题描述

我从CSV中导入,大致以

格式输入数据

  {'Field1':3000,'Field2 ':6000,'RandomField':5000} 

字段的名称是动态的。 (嗯,他们是动态的,可能有更多的Field1和Field2,但我知道Field1和Field2总是在那里。



能够将这个字典传入我的类allMyFields,以便我可以访问上面的数据作为属性。

  class allMyFields: 
#我想我需要包括这些,以允许暗示在Komodo。我想。
self.Field1 =无
self.Field2 =无

def __init __ self,dictionary):
for k,v in dictionary.items():
self.k = v
#of当然,这不工作我最后做

q = {'Field1':3000,'Field2','$' :6000,'RandomField':5000}
instance = allMyFields(q)
#理想情况下我可以这样做
print q.Field1
/ pre>

有什么建议吗?至于为什么 - 我想能够利用代码提示,并将数据导入一个名为data 因为我一直在做不负任何这一点。



(因为变量名直到运行时才解决,我还是要向Komodo抛出一个骨头 - 我认为self.Field1 = None足够了。



那么 - 我该怎么做我想要的呢?或者是我设计得不好的非python树?

解决方案

您可以使用 setattr (注意:不是每个字符串都是有效的属性名称!):

 >>> class AllMyFields:
... def __init __(self,dictionary):
... for k,v in dictionary.items ):
... setattr(self,k,v)
...
>>> o = AllMyFields({'a':1,'b':2 })
>>> oa
1

编辑:让我们解释上述代码和 SilentGhost的回答。上面的代码片段创建了一个类,其中实例属性基于给定的字典。



根据您的具体情况,这些解决方案中的任何一个可能更适合。你很容易创建一个或多个类实例吗?如果答案是一个,你可以完全跳过对象创建,只构造类型(因此与SilentGhost的答案)。


I'm importing from a CSV and getting data roughly in the format

{ 'Field1' : 3000, 'Field2' : 6000, 'RandomField' : 5000 }

The names of the fields are dynamic. (Well, they're dynamic in that there might be more than Field1 and Field2, but I know Field1 and Field2 are always going to be there.

I'd like to be able to pass in this dictionary into my class allMyFields so that I can access the above data as properties.

class allMyFields:
    # I think I need to include these to allow hinting in Komodo. I think.
    self.Field1 = None
    self.Field2 = None

    def __init__(self,dictionary):
        for k,v in dictionary.items():
            self.k = v 
            #of course, this doesn't work. I've ended up doing this instead
            #self.data[k] = v
            #but it's not the way I want to access the data. 

q = { 'Field1' : 3000, 'Field2' : 6000, 'RandomField' : 5000 }
instance = allMyFields(q)
# Ideally I could do this.
print q.Field1

Any suggestions? As far as why -- I'd like to be able to take advantage of code hinting, and importing the data into a dictionary called 'data' as I've been doing doesn't afford me any of that.

(Since the variable names aren't resolved till runtime, I'm still going to have to throw a bone to Komodo - I think the self.Field1 = None should be enough.

So - how do I do what I want? Or am I barking up a poorly designed, non-python tree?

解决方案

You can use setattr (be careful though: not every string is a valid attribute name!):

>>> class AllMyFields:
...     def __init__(self, dictionary):
...         for k, v in dictionary.items():
...             setattr(self, k, v)
... 
>>> o = AllMyFields({'a': 1, 'b': 2})
>>> o.a
1

Edit: let me explain the difference between the above code and SilentGhost's answer. The above code snippet creates a class of which instance attributes are based on a given dictionary. SilentGhost's code creates a class whose class attributes are based on a given dictionary.

Depending on your specific situation either of these solutions may be more suitable. Do you plain to create one or more class instances? If the answer is one, you may as well skip object creation entirely and only construct the type (and thus go with SilentGhost's answer).

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

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