python中的Object属性

2024-04-19 20:27:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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解释为服务器呢。你知道吗

提前谢谢


Tags: 文件inpyimportclientforserverconf
3条回答
s = __import__('conf1')
temp = 'server'
for v in getattr(conf, temp): # .keys() not required
    print v

您正在模块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

相关问题 更多 >