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
.
精彩评论