首页 > 代码库 > python将对象名的字符串类型,转化为相应对象的操作方法
python将对象名的字符串类型,转化为相应对象的操作方法
在实际使用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将对象名的字符串类型,转化为相应对象的操作方法
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。