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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM