在实际使用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

python将对象名的字符串类型,转化为相应对象的操作方法的更多相关文章

  1. Json对象与Json字符串的转化、JSON字符串与Java对象的转换

    一.Json对象与Json字符串的转化 1.jQuery插件支持的转换方式: $.parseJSON( jsonstr ); //jQuery.parseJSON(jsonstr),可以将json字符 ...

  2. Json对象与Json字符串的转化、JSON字符串与Java对象的转换(转)

    一.Json对象与Json字符串的转化 1.jQuery插件支持的转换方式: $.parseJSON( jsonstr ); //jQuery.parseJSON(jsonstr),可以将json字符 ...

  3. Python基础(3) - 数据类型:2字符串类型

    Python字符串的表示有三种方法: 1.单引号(') >>>a = 'I love python. ' 2.双引号(") >>>a = " I ...

  4. JSON数组对象和JSON字符串的转化,map和JSON对象之间的转化

    这种用法包括前端和后端: 前端: 1. 转化为JSON对象方便操作 var jsonObj = JSON.parse(str); 得到的是一个json数组对象,可以通过 for (var p in j ...

  5. 将DataTable转换为List<T>对象遇到问题:类型“System.Int64”的对象无法转换为类型“System.Int32”。

    可以利用反射将DataTable转换为List<T>对象:原始链接http://www.jb51.net/article/67386.htm 但是该方法在DataTable里某个字段类型是 ...

  6. Python进阶:如何将字符串常量转化为变量?

    前几天,我们Python猫交流学习群 里的 M 同学提了个问题.这个问题挺有意思,经初次讨论,我们认为它无解. 然而,我认为它很有价值,应该继续思考怎么解决,所以就在私密的知识星球上记录了下来. 万万 ...

  7. python入门及数字、字符串类型

    目录 python开发框架 开发 1. 开发语言 2. 语言比对 3. python安装 4. Python开发IDE:pycharm ,eclipse python入门 1. 第一句Python 2 ...

  8. Json对象与Json字符串的转化

    1.jQuery插件支持的转换方式: $.parseJSON( jsonstr ); //jQuery.parseJSON(jsonstr),可以将json字符串转换成json对象 2.浏览器支持的转 ...

  9. python 使用函数名的字符串调用函数(4种方法)_black-heart的专栏-CSDN博客 https://blog.csdn.net/mrqingyu/article/details/84403924

    funcs = ['fetch_data_' + i for i in ( 'activities', 'banners', 'server_list')]# from operator import ...

随机推荐

  1. 框架源码系列十二:Mybatis源码之手写Mybatis

    一.需求分析 1.Mybatis是什么? 一个半自动化的orm框架(Object Relation Mapping). 2.Mybatis完成什么工作? 在面向对象编程中,我们操作的都是对象,Myba ...

  2. 删除SQL架构的用户

    ALTER AUTHORIZATION ON SCHEMA::db_owner TO db_owner

  3. tensorflow, TypeError:'Tensor' object is not callable

    解决办法:两个tensor相乘,需要加“*”.

  4. LiDAR、LAS、LAS Dataset与点云

    LiDAR Light Detection And Ranging,激光探测及测距,是一种光学遥感技术,使用激光对地球表面的密集采样,产生高精度X.Y.Z测量值. 激光雷达系统的主要硬件组成部分包括一 ...

  5. 入围T00ls 2018风云人物

    今天早上打开T00ls,发现成功入围了<T00ls第六届(2018)年度人物风云榜>,共34名年度人物,每个id可投10票,34选10. T00ls是当前国内为数不多的民间网络信息安全研究 ...

  6. nginx && apache 图片代理

    location ~ /mmopen/ { proxy_set_header Host thirdwx.qlogo.cn; rewrite /(.+)$ /$ break; proxy_pass ht ...

  7. mac sed 使用踩坑实录

    [转自别处] 比如我sed想做文件原地的替换,但是怎么写都出错,错误提示还莫名其妙,后来多方搜索才知道Mac上的sed如果参数有-i就必须加上备份指令,即-i后添加任意字符,那些字符就作为备份文件的后 ...

  8. Tensorflow一些常用基本概念与函数(1)

    为了快速的熟悉TensorFlow编程,下面从一段简单的代码开始: import tensorflow as tf #定义‘符号’变量,也称为占位符 a = tf.placeholder(" ...

  9. filter滤镜效果(css3属性)

    <!DOCTYPE html> <html> <head> <style> img { width: 33%; height: auto; float: ...

  10. NFC中国-中国第一NFC论坛,NFC中文论坛+NFC技术社区+NFC_电子发烧友网【申明:来源于网络】

    NFC中国-中国第一NFC论坛,NFC中文论坛+NFC技术社区[申明:来源于网络] NFC中国-中国第一NFC论坛,NFC中文论坛:http://nfcchina.org/forum.php NFC技 ...