eval() 函数用来执行一个字符串表达式,并返回表达式的值。
x = 7
y = eval( '3 * x' )
print(y)
21
更好用的地方体现在:
model_choice = 'TransformerTime_NL' # name of the model class
model_file = eval(model_choice) #直接执行调用模型这一步,而不是字符串赋值
model = model_file(n_diagnosis_codes, batch_size, options)
model.train()
等价于
model = TransformerTime_NL(n_diagnosis_codes, batch_size, options)
model.train()
当既需要字符串类型的模型名称,又需要同时调用模型的时候,该功能显得异常有效