importlib
实现了__import__()
方法
方法 | 描述 |
---|---|
importlib.__import__(name, globals=None, locals=None, fromlist=(), level=0) | 内置__import__() 的实现 |
importlib.import_module(name, package=None) | 导入一个module |
importlib.find_loader(name, path=None) | Find the loader for a module, optionally within the specified path. If the module is in sys.modules, then sys.modules[name].loader is returned |
importlib.invalidate_caches() | 清除缓存 |
importlib.reload(module) | 重新载入 |
例子:
--testpack
--__init__
--testmod.py
test.py
testmod.py
class Person(object):
def __init__(self, name):
self.name = name
def say(self):
print(f"hello {self.name}")
test.py
# 常规的调用方法
# import testpack.testmod
# p = testmod.Person("wang")
# p.say()
# 反射方法,导入模块
# import importlib
# testmod = importlib.import_module("testpack.testmod") # 反射导入模块(.py)
# p = testmod.Person('wang')
# p.say()
# 反射方法,导入模块和类
import importlib
testmod = importlib.import_module("testpack.testmod") # 反射导入模块(.py)
Person = getattr(testmod,"Person") # 反射导入模块中的类
p = Person("wang")
p.say()
例子
app.py
from utils import send_msgs
send_msgs('.....')
settings.py
MSG_LIST = [
"utils.email.Email",
"utils.msg.Msg",
"utils.wechat.WeChat",
]
utils.__init__.py
import settings
import importlib
def send_msgs(msg):
"""
导入设置里配置的功能
:param msg:
:return:
"""
for path in settings.MSG_LIST:
m,c = path.rsplit('.',maxsplit=1) # 切分配置里的模块路径(注意不是文件路径)
md = importlib.import_module(m) # 导入模块,类似于java中的反射机制
obj = getattr(md,c)() # 获得模块的里的类,后面加()实例化
obj.send(msg) # 调用类的方法
base.py
class Base(object):
def send(self,msg):
raise NotImplementedError('...') # 这样写相当于java中的接口
msg.py
from .base import Base
class Msg(Base):
def send(self, msg):
print("发送短信"+msg)
email.py
from .base import Base
class Email(Base):
def send(self,msg):
print("发送邮件"+msg)
wechat.py
from .base import Base
class WeChat(Base):
def send(self,msg):
print("发微信"+msg)