2024-04-19 20:27:34 发布
网友
我在conf1.py文件中有以下内容
server = { '1':'ABC' '2':'CD' } client = { '4':'jh' '5':'lk' }
现在在其他python文件中
s=__import__('conf1') temp='server' for v in conf.temp.keys(): print v
并得到conf对象没有属性temp的错误 那么我如何才能将temp解释为服务器呢。你知道吗
提前谢谢
s = __import__('conf1') temp = 'server' for v in getattr(conf, temp): # .keys() not required print v
您正在模块conf中查找名为temp的变量。如果要基于字符串中的名称动态获取变量,请使用getattr(conf, temp)而不是conf.temp。你知道吗
conf
temp
getattr(conf, temp)
conf.temp
你想要:
import conf1 temp=conf1.server for v in temp.keys(): print v
但是,您不需要.keys()来迭代dict的键,只需执行以下操作:
for v in temp: print v
您正在模块
conf
中查找名为temp
的变量。如果要基于字符串中的名称动态获取变量,请使用getattr(conf, temp)
而不是conf.temp
。你知道吗你想要:
但是,您不需要.keys()来迭代dict的键,只需执行以下操作:
相关问题 更多 >
编程相关推荐