Python object attribute

I have the following conf1.py file

server = { '1':'ABC' '2':'CD' } client = { '4':'jh' '5':'lk' } 

Now in another python file

 s=__import__('conf1') temp='server' for v in conf.temp.keys(): print v 

And getting an error in which the conf object does not have the temp attribute So, how can I make it possible to interpret temp as a server.

Thanks at Advance

+4
source share
3 answers
 s = __import__('conf1') temp = 'server' for v in getattr(conf, temp): # .keys() not required print v 
+2
source

Do you want to:

 import conf1 temp=conf1.server for v in temp.keys(): print v 

however you do not need .keys () to iterate over the dict keys, you can simply do:

 for v in temp: print v 
+2
source

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

0
source

Source: https://habr.com/ru/post/1346081/


All Articles