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()

 

posted @ 2019-05-07 22:28  大西瓜Paul  阅读(1416)  评论(0编辑  收藏  举报
/*增加返回顶部按钮*/ 返回顶部 /*给标题增加蓝色背景长条*/