python字符串反射成变量

python中如果我们获的一个字符串为'test',恰好有一个变量为test,如何获取到该test的值呢?

方法1:用eval函数:

dbconfig.py如下:

#encoding=utf-8

#定义数据库(根据excel中的db值,到这里找到同样的变量名)

test={'user':'root', 'password':'','host':'localhost','port':3306,'dbase':'test'}

test2={'user':'root2', 'password':'22','host':'localhost22','port':3306,'dbase':'test2'}

HelloTest.py如下

#encoding=utf-8

import dbconfig

class Jdbc_pymysql():

    def getdbinfo(self,line):

        db_name = line['db']

        dbinfor = eval('dbconfig.'+db_name)

        print(dbinfor)

if __name__=='__main__':

    line={'db':'test'}

Jdbc_pymysql().getdbinfo(line)

执行结果:打印出:{'user': 'root', 'password': '', 'host': 'localhost', 'port': 3306, 'dbase': 'test'}

方法2:用反射(变量要放在一个类中才行),比如:

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'}

原文地址:https://www.cnblogs.com/retest/p/13087236.html