最佳答案
我从一个 CSV 导入和获得数据的大致格式
{ 'Field1' : 3000, 'Field2' : 6000, 'RandomField' : 5000 }
字段的名称是动态的。(嗯,它们是动态的,因为它们可能比 Field1和 Field2更多,但是我知道 Field1
和 Field2
总是在那里。
我希望能够将这个字典传递到我的类 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
应该足够了。)
那么,我该如何做我想做的事情呢? 或者我是否正在创建一个设计糟糕的、非蟒蛇的树呢?