从字典创建类实例属性

从字典创建类实例属性

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

问题描述

我正在从CSV导入,并以大致的格式获取数据

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

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

字段的名称是动态的. (好吧,它们是动态的,它可能不止是Field1和Field2,但我知道Field1Field2总是会存在的.

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.

我希望能够将此字典传递给我的课程allMyFields,以便我可以将以上数据作为属性来访问.

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

有什么建议吗?至于为什么-我希望能够利用代码提示功能,并且将数据导入名为data的字典中,而我一直在做这些事,我却一无所获.

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.

(由于直到运行时才解析变量名,所以我仍然不得不向Komodo扔骨头-我认为self.Field1 = None应该足够了.)

(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.)

所以-我该怎么做?还是我在设计一棵设计欠佳的非Python树?

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

推荐答案

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

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

让我解释一下以上代码与.上面的代码片段创建了一个类,这些类的 instance属性基于给定的字典. SilentGhost的代码创建一个类,该类的 class属性基于给定的字典.

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.

根据您的具体情况,这两种解决方案中的任何一种都可能更合适.您是否简单地创建一个或多个类实例?如果答案是一个,那么您也可以完全跳过对象的创建,而仅构造类型(并使用SilentGhost的答案).

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).

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

07-26 08:43