zoukankan      html  css  js  c++  java
  • 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'}

  • 相关阅读:
    怎么为学生布置作业
    新学期的第一节Android课
    RUCSE小组博客列表
    test
    个人最终总结
    黄金点小游戏的设计与实现
    WordCount 程序的实现
    阅读下面程序,请回答如下问题:
    Visual Studio 2015的安装和简单的单元测试
    构建之法--软件工程学习随笔之二
  • 原文地址:https://www.cnblogs.com/retest/p/13087236.html
Copyright © 2011-2022 走看看