🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] ## 1. _bootstrap模块与import_module方法 ~~~ __author__ = 'dailin' from importlib import _bootstrap from importlib import import_module def import_module_bootstrap(name, package=None): """Import a module. The 'package' argument is required when performing a relative import. It specifies the package to use as the anchor point from which to resolve the relative import to an absolute import. """ level = 0 if name.startswith('.'): if not package: msg = ("the 'package' argument is required to perform a relative " "import for {!r}") raise TypeError(msg.format(name)) for character in name: if character != '.': break level += 1 return _bootstrap._gcd_import(name[level:], package, level) def say(): print("come on!") import sys print(sys.path) module = import_module("pythontest.module_test") module1 = import_module_bootstrap("pythontest.module_test") print(module == module1) if hasattr(module,"say"): getattr(module,'say')() print("=================") for key in dir(module): print(key) print("=================") ppeople_obj = getattr(module,'People')() for key in dir(ppeople_obj): print(key) ~~~ **module_test:** ~~~ __author__ = 'dailin' from importlib import import_module class People(object): def eat(self): print("I am a human,I can eat!") def say(): print("hello new day,come on!") if __name__ == '__main__': module = import_module('pythontest.module_test') ~~~ **结果:** ~~~ ['E:\\PythonTest\\pythonpackage', 'E:\\PythonTest', 'D:\\Python\\Python36\\python36.zip', 'D:\\Python\\Python36\\DLLs', 'D:\\Python\\Python36\\lib', 'D:\\Python\\Python36', 'D:\\Python\\Python36\\lib\\site-packages', 'D:\\Python\\Python36\\lib\\site-packages\\psutil-5.2.2-py3.6-win-amd64.egg', 'D:\\Python\\Python36\\lib\\site-packages\\helloworld-0.1-py3.6.egg', 'D:\\Python\\Python36\\lib\\site-packages\\sayhello-0.1-py3.6.egg', 'D:\\Python\\Python36\\lib\\site-packages\\win32', 'D:\\Python\\Python36\\lib\\site-packages\\win32\\lib', 'D:\\Python\\Python36\\lib\\site-packages\\Pythonwin'] True hello new day,come on! ================= People __author__ __builtins__ __cached__ __doc__ __file__ __loader__ __name__ __package__ __spec__ import_module say ================= __class__ __delattr__ __dict__ __dir__ __doc__ __eq__ __format__ __ge__ __getattribute__ __gt__ __hash__ __init__ __init_subclass__ __le__ __lt__ __module__ __ne__ __new__ __reduce__ __reduce_ex__ __repr__ __setattr__ __sizeof__ __str__ __subclasshook__ __weakref__ eat # people的eat方法 ~~~ 1. _bootstrap._gcd_import与import_module都是根据模块的字符串路径在程序的过程中动态导入模块,具体的区别还没了解,_bootstrap._gcd_import是在scrapy的源码中看到的。 ### dir() 函数 dir() 函数不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。如果参数包含方法__dir__(),该方法将被调用。如果参数不包含__dir__(),该方法将最大限度地收集参数信息。 例如上面的 1. 查看模块属性 ~~~ for key in dir(module): print(key) ~~~ 会输出该模块的所有属性: ~~~ People # 模块中的类 __author__ # 作者 __builtins__ __cached__ __doc__ # 注释 __file__ # 文件(路径) __loader__ __name__ __package__ __spec__ import_module # 模块中导入的其他模块 say # 模块中的方法 ~~~ 2. 查看People对象 ~~~ print("=================") ppeople_obj = getattr(module,'People')() for key in dir(ppeople_obj): print(key) ~~~ 结果 ~~~ ================= __class__ __delattr__ __dict__ __dir__ __doc__ __eq__ __format__ __ge__ __getattribute__ __gt__ __hash__ __init__ __init_subclass__ __le__ __lt__ __module__ __ne__ __new__ __reduce__ __reduce_ex__ __repr__ __setattr__ __sizeof__ __str__ __subclasshook__ __weakref__ eat # People对象的eat方法 ~~~ ### sys.modules > sys.modules: > 是一个全局字典,该字典是python启动后就加载在内存中。每当程序员导入新的模块,sys.modules都将记录这些模块。字典sys.modules对于加载模块起到了缓冲的作用。当某个模块第一次导入,字典sys.modules将自动记录该模块。当第二次再导入该模块时,python会直接到字典中查找,从而加快了程序运行的速度。 > ~~~ print(sys.modules) ~~~ 如图,pythontest.module_test模块被动态的导入了,并放到了sys.modules中 ~~~ {'builtins': <module 'builtins' (built-in)>, 'sys': <module 'sys' (built-in)>, '_frozen_importlib': <module 'importlib._bootstrap' (frozen)>, '_imp': <module '_imp' (built-in)>, '_warnings': <module '_warnings' (built-in)>, '_thread': <module '_thread' (built-in)>, '_weakref': <module '_weakref' (built-in)>, '_frozen_importlib_external': <module 'importlib._bootstrap_external' (frozen)>, '_io': <module 'io' (built-in)>, 'marshal': <module 'marshal' (built-in)>, 'nt': <module 'nt' (built-in)>, 'winreg': <module 'winreg' (built-in)>, 'zipimport': <module 'zipimport' (built-in)>, 'encodings': <module 'encodings' from 'D:\\Python\\Python36\\lib\\encodings\\__init__.py'>, 'codecs': <module 'codecs' from 'D:\\Python\\Python36\\lib\\codecs.py'>, '_codecs': <module '_codecs' (built-in)>, 'encodings.aliases': <module 'encodings.aliases' from 'D:\\Python\\Python36\\lib\\encodings\\aliases.py'>, 'encodings.utf_8': <module 'encodings.utf_8' from 'D:\\Python\\Python36\\lib\\encodings\\utf_8.py'>, '_signal': <module '_signal' (built-in)>, '__main__': <module '__main__' from 'E:/PythonTest/pythonpackage/packagtest.py'>, 'encodings.latin_1': <module 'encodings.latin_1' from 'D:\\Python\\Python36\\lib\\encodings\\latin_1.py'>, 'io': ..... 'heapq': <module 'heapq' from 'D:\\Python\\Python36\\lib\\heapq.py'>, '_heapq': <module '_heapq' (built-in)>, 'itertools': <module 'itertools' (built-in)>, 'reprlib': <module 'reprlib' from 'D:\\Python\\Python36\\lib\\reprlib.py'>, '_collections': <module '_collections' (built-in)>, 'weakref': <module 'weakref' from 'D:\\Python\\Python36\\lib\\weakref.py'>, 'collections.abc': <module 'collections.abc' from 'D:\\Python\\Python36\\lib\\collections\\abc.py'>, 'encodings.cp437': <module 'encodings.cp437' from 'D:\\Python\\Python36\\lib\\encodings\\cp437.py'>, 'importlib': <module 'importlib' from 'D:\\Python\\Python36\\lib\\importlib\\__init__.py'>, 'importlib._bootstrap': <module 'importlib._bootstrap' (frozen)>, 'importlib._bootstrap_external': <module 'importlib._bootstrap_external' (frozen)>, 'warnings': <module 'warnings' from 'D:\\Python\\Python36\\lib\\warnings.py'>, *'pythontest': <module 'pythontest' from 'E:\\PythonTest\\pythontest\\__init__.py'>, 'pythontest.module_test': <module 'pythontest.module_test' from 'E:\\PythonTest\\pythontest\\module_test.py'>}* ~~~