# encoding=utf-8
# 加载模块
# os = __import__("os")
# 推荐使用
import importlib
os = importlib.import_module("os")
print(os.path.abspath(__file__))
# 获得特定函数
def get_func(module_name, function_name):
module = __import__(module_name)
return getattr(module, function_name)
# Python 的辨识符不允许有”-”
f = get_func("builtin-apply-example", "func")
f("aaa", "bbb")
# ('aaa', 'bbb')
# 函数实现延迟导入 lazy module loading
class LazyImport(object):
def __init__(self, module_name):
self.module_name = module_name
self.module = None
def __getattr__(self, name):
if self.module is None:
self.module = __import__(self.module_name)
return getattr(self.module, name)
# string 模块只在第一次使用的时候导入
string = LazyImport("string")
print(string.lowercase)
# abcdefghijklmnopqrstuvwxyz