python中通过string类名获得实例

原文:https://bytes.com/topic/python/answers/42866-how-create-object-instance-string

Ksenia Marasanova的回答。

该操作可实现类似java中的‘反射’

-------如果是在同一个命名空间
clazz = globals()['classname']
instance= clazz()

 ------如果在其它module,先import导入该module
import module
clazz= getattr(module, 'classname')
instance = clazz()

猜你喜欢

转载自www.cnblogs.com/2333/p/9187386.html