python字符串反射成变量,
python字符串反射成变量,
python中如果我们获的一个字符串为'test',恰好有一个变量为test,如何获取到该test的值呢?
要用到反射,比如:
print getattr(Instance , 'age', 'not find') #如果Instance 对象中有属性age则打印self.age的值,否则打印'not find'
示例如下:
#encoding=utf-8
#定义数据库(根据excel中的db值,到这里找到同样的变量名)
class DbConfig():
def __init__(self):
self.test={'user':'root', 'password':'','host':'localhost','port':3306,'dbase':'test'}
self.test2={'user':'root2', 'password':'22','host':'localhost22','port':3306,'dbase':'test2'}
if __name__=='__main__':
cf=DbConfig()
print(cf.test)
s='test2'
print (getattr(cf,s,'not find'))
将打印出:
{'user': 'root', 'password': '', 'host': 'localhost', 'port': 3306, 'dbase': 'test'}
{'user': 'root2', 'password': '22', 'host': 'localhost22', 'port': 3306, 'dbase': 'test2'}
相关内容
- 暂无相关文章
评论关闭