开发者

Object attribute in python

I have following in conf1.py file

server = { 
  '1':'ABC'
  '2':'CD' 
}

client = {
  '4':'jh'
  '5':'lk' 
}

Now in other python file

s=__import__('conf1')
temp='server'
for v in conf.temp开发者_JAVA百科.keys():
    print v

And getting the error that conf object don't have attribute temp So how can I make this possible to interpret temp as server.

Thanks in Advance


s = __import__('conf1')
temp = 'server'
for v in getattr(conf, temp): # .keys() not required
    print v


You want:

import conf1

temp=conf1.server 

for v in temp.keys(): print v

however you don't need .keys() to iterate over the dict's keys, you can just do:

for v in temp: print v


You are looking for a variable named temp in the module conf. If you want to dynamically get a variable based on a name in a string, use getattr(conf, temp) instead of conf.temp.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜