我正在将代码从python2移植到python3。Python 2版本使用此代码段成功实例化一个类:
#at this point, "module_name" is just a string
module = __import__(module_name, globals(), locals(), [])
#class_name is just a string
my_class = getattr(module, class_name)
class_instance = my_class()
在Python3中,同样的代码失败,出现AttributeError,表示我的模块名没有类名的属性。我在这里读到的其他类似问题建议getattr应该在python3中用于此任务,但对我来说不是。你知道吗
我误解了什么?有没有更好的方法从字符串实例化类?你知道吗
目前没有回答
相关问题 更多 >
编程相关推荐