博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python将对象名的字符串类型,转化为相应对象的操作方法
阅读量:4451 次
发布时间:2019-06-07

本文共 5312 字,大约阅读时间需要 17 分钟。

在实际使用Python的过程中,遇到了一个问题,就是定义一个数组,数组内容为对应类名字的字符串。

 

此时在调用对应的类,生成实例时,需要将字符串转化为相应的类,之后再进行实例化。

 

# coding : utf-8 import time from OffLineGateway import OffLineGateway from OffLineTS import OffLineTS import copy class PlayTest(object):     def __init__(self, file):         self.file = file         get_obj = file.split('.')[0]         module = __import__(get_obj)         self.server_name = getattr(module, get_obj)()         self.test_param_file = r'./' + file.split('.')[0] + r"param" + time.strftime("%H%M%S", time.localtime()) + ".txt"         self.test_func_file = r'./' + file.split('.')[0] + r"func" + time.strftime("%H%M%S", time.localtime()) + ".txt"     def set_function(self, num, variable):         flag = 0         content = ""         file_object = open(self.file, 'r', encoding='utf-8')         for line in file_object:             string = r'    def test_exe_param' + str(num) + r'(self):'             if line.__contains__(string) and flag == 0:                 flag = 1                 content += '    def test_exe_param' + str(num) + '_' + str(variable) + r'(self):\n'             else:                 if line.__contains__("    def test_exe_param") and flag == 1:                     break                 elif flag == 1:                     if line.__contains__('self.assertFalse(True, '):                         content += line                         content += '\n        if get_return_code != "000000":\n'                         content += '            self.assertEqual(get_errormsg, self.server.read_config' \                                    '(self.config_file, get_return_code))\n'                         content += '        else:\n'                         content += '            self.assertFalse(True, "没有对应的错误码。")\n\n'                         break                     else:                         if line.__contains__('result = self.server.get_result(self.ip, self.param'):                             new_line = line.replace(str(num), str(num) + "_" + str(variable))                             content += '\n' + new_line                         elif line.__contains__('self.param' + str(num) + '['):                             new_line = line.replace(str(num), str(num) + "_" + str(variable))                             content += '\n' + new_line                         else:                             content += line                 else:                     pass         return content     def get_param(self):         of = self.server_name.setUp()         for i in range(1, 100):             try:                 j = 1                 param = eval("of['self'].param" + str(i))                 print(i)                 port = list(param.keys())[0]                 temp = copy.deepcopy(param)                 for key in param[port][1].keys():                     param[port][1][key] = ""                     with open(self.test_param_file, "a", encoding="utf-8") as f:                         f.write("        self.param" + str(i) + "_" + str(j) + " = " + str(param) + "\n")                     # print("self.param" + str(i) + "_" + str(j) + " = " + str(param))                     with open(self.test_func_file, "a", encoding="utf-8") as f:                         f.write(self.set_function(i, j))                     # print(self.set_function(i, j))                     j += 1                     param[port][1][key] = temp['gw'][1][key]                 for key in param[port][1].keys():                     param[port][1][key] = ""                 with open(self.test_param_file, "a", encoding="utf-8") as f:                     f.write("        self.param" + str(i) + "_" + str(j) + " = " + str(param) + "\n")                 # print("self.param" + str(i) + "_" + str(j) + " = " + str(param))                 with open(self.test_func_file, "a", encoding="utf-8") as f:                     f.write(self.set_function(i, j))                 # print(self.set_function(i, j))                 j += 1                 param[port][1] = {}                 with open(self.test_param_file, "a", encoding="utf-8") as f:                     f.write("        self.param" + str(i) + "_" + str(j) + " = " + str(param) + "\n")                 # print("self.param" + str(i) + "_" + str(j) + " = " + str(param))                 with open(self.test_func_file, "a", encoding="utf-8") as f:                     f.write(self.set_function(i, j))                 # print(self.set_function(i, j))             except AttributeError as ae:                 print("没有了。")                 break if __name__ == '__main__':     file_name = ['OffLineGateway', 'OffLineTS']     for name in file_name:         print(name)         test = PlayTest(name + ".py")         test.get_param()         time.sleep(1.0)

+++++++++++++++++++++++++++++++++++++++分割线+++++++++++++++++++++++++++++++++++++++

 

 

方法一:

class obj(object): 

      pass 

 a = eval('obj()')

 

方法二:

如果是经常需要这样可以

#将用来创建对象的字符串预编译成code对象.

create_obj = compile('obj()', 'create_obj.py', 'eval') 

#需要创建的时候, 直接用code对象, 这样会有效率上的提升. #因为code对象是预编译过的, 而不用每次去编译

a = eval(create_obj)

 

方法三:

file_name  模块名  

 

 module = __import__(file_name)

 AClass = getattr(module, class_name_str)()

 a = AClass() 或

obj = new.instance(AClass)

方法四: 也可以使用global(),locals(),dir()这类获取对象名和对象对应的函数 

 

转自:http://www.th7.cn/Program/Python/201510/666094.shtml

转载于:https://www.cnblogs.com/wozijisun/p/7099097.html

你可能感兴趣的文章
2019秋招复习笔试--手写代码
查看>>
2019秋招复习笔记--智力题
查看>>
MySQL学习笔记
查看>>
2019秋招面试复习 项目重点提问
查看>>
面试题
查看>>
DS博客作业08-课程总结
查看>>
利用Python爬虫刷店铺微博等访问量最简单有效教程
查看>>
浅谈软件测试与墨菲定律
查看>>
文件安全复制之 FastCopy
查看>>
强烈推荐美文之《从此刻起,我要》
查看>>
MYSQL中数据类型介绍
查看>>
评估软件上线标准
查看>>
敏捷开发流程
查看>>
APP兼容性测试(三)测试方案设计
查看>>
leetcode 412. Fizz Buzz
查看>>
对Netflix Ribbon的Loadbalancer类源码设计合理性的一点质疑
查看>>
关于日历的算法
查看>>
[QT编程]QT实现的一个渐隐渐显窗体
查看>>
在Web工程中引入Jquery插件报错解决方案
查看>>
大学总结之影响我最深的十本书
查看>>