getattr(模块名称,类名称)python2和python3之间的区别

2024-04-20 10:05:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在将代码从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中用于此任务,但对我来说不是。你知道吗

我误解了什么?有没有更好的方法从字符串实例化类?你知道吗


Tags: 实例代码name版本stringismy代码段