python中类的属性可以是字典嘛,在Python中从字典中创建类实例属性

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值