如何在Python中将字符串转换为类名?

时间:2019-06-13 13:19:56

标签: python flask

我从HTML表单中获得了一个字符串 selected_optimizer

selected_optimizer = str(request.form['optimizer'])
print(selected_optimizer) #AdamOptimizer

我记得功能

import tensorflow as tf

train_model(
    my_optimizer=tf.train.AdamOptimizer(learning_rate=0.05))

是否可以将字符串转换为Class名称并获得如下所示的内容:

train_model(
    my_optimizer=tf.train.selected_optimizer(learning_rate=0.05))

2 个答案:

答案 0 :(得分:2)

使用字典。

optimizers = {
    "AdamOptimizer": tf.train.AdamOptimizer,
    "OtherOptimizer": ....,
}
selected_optimizer = optimizers[request.form['optimizer']]
train_model(my_optimizer=selected_optimizer(learning_rate=0.05))

答案 1 :(得分:1)

import tensorflow as tf

selected_optimizer = str(request.form['optimizer'])
print(selected_optimizer) #AdamOptimizer

eval("train_model(my_optimizer=tf.train."+selected_optimizer+"(learning_rate=0.05))")

使用eval比这容易得多。根据我的

def AdamOptimizer():
    print("hi")

strr="AdamOptimizer"

eval(strr+'()')