Python---根据字符串导入包(importlib)
import importlib o = importlib.import_module("xx.oo") # o 为 <module 'xx.oo' from 'D:\\locker\\importlib_demo\\xx\\oo.py'> print(o.NAME) p = o.Person("cmb") p.dream()
import importlib # 根据字符串导入模块 # 通常用来导入包下面的模块 o = importlib.import_module("xx.oo") s2 = "Person" # 由字符串找函数、方法、类, 利用反射 the_var = getattr(o, "NAME") print(the_var) the_class = getattr(o, s2) p2 = the_class("小和牛") p2.dream() print(the_class) # <class 'xx.oo.Person'> print(o) # <module 'xx.oo' from 'D:\\locker\\importlib_demo\\xx\\oo.py'> print(o.NAME) p = o.Person("cmb") p.dream()