class - 从字典创建类实例属性?

标签 class python komodo

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

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

字段的名称是动态的。 (嗯,它们是动态的,因为可能不止 Field1 和 Field2,但我知道 Field1Field2 总是会在那里。

我希望能够将此字典传递到我的类 allMyFields 中,以便我可以将上述数据作为属性访问。

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 的字典中并没有为我提供任何这些.

(由于变量名直到运行时才解析,我仍然不得不向 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})
>>> o.a
1

编辑:让我解释一下上面的代码和SilentGhost's answer的区别。 .上面的代码片段创建了一个类,其中 instance attributes 基于给定的字典。 SilentGhost 的代码创建了一个类,其类属性基于给定的字典。

根据您的具体情况,这些解决方案中的任何一个都可能更合适。您是否打算创建一个或多个类实例?如果答案是 1,您不妨完全跳过对象创建,只构造类型(因此选择 SilentGhost 的答案)。

关于class - 从字典创建类实例属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1639174/

相关文章:

python - 打开pyxl "Numbers Stored as Text"

python - 用 Python 编写 Komodo Edit 扩展

c++ - Qt继承和类构造函数混淆

c++ - "public"和 "private"可见性修饰符的缩进

python - 如何正确运行类中方法内的方法(python)

Python opencv + flask ,VideoCamera打开但不显示视频源

c++ - 如何知道复制构造函数被调用?

python - 如何使用 python 在 selenium webdriver 中将 cookie 设置为特定域?

python - 无法在 Komodo 中创建和运行新的 python 文件

python - 使用 Komodo 和 Anaconda 在 python 中导入 scipy.misc.pilutil?