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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值