- importlib
importlib允许程序员创建他们自定义的对象。imp的模块在Python3.4中被去掉。
用途扩展自定义函数
#!/usr/bin/env python
#-*- coding = utf-8 -*-
import importlib
import imp
import sys
# Syntax sugar.
_ver = sys.version_info
#: Python 2.x?
is_py2 = (_ver[0] == 2)
#: Python 3.x?
is_py3 = (_ver[0] == 3)
def get_imported_module_from_file(file_path):
""" import module from python file path and return imported module
"""
if is_py3:
imported_module = importlib.machinery.SourceFileLoader(
'module_name', file_path).load_module()
elif is_py2:
imported_module = imp.load_source('module_name', file_path)
else:
raise RuntimeError("Neither Python 3 nor Python 2.")
return imported_module
if __name__ == "__main__":
imported_module = get_imported_module_from_file("buildin.py")
# 动态引入对象的属性
print(dir(imported_module))
# todo 调用引入文件的方法
phone = imported_module.getPhone()
print(f"手机号 : {phone}")
#!/usr/bin/env python
#-*- coding = utf-8 -*-
def setPhone(phone):
return phone
def getPhone():
return "15365878954"
结果
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'getPhone', 'setPhone']
手机号 : 15365878954
- _import_ 实现
imported_module = __import__("buildin")
print(dir(imported_module))
phone = imported_module.getPhone()
print(f"手机号 : {phone}")
结果
['__builtins__', '__cached__', '__doc_