如何通过Python实现惰性导入(lazy)的详细方法?
- 内容介绍
- 文章标签
- 相关推荐
本文共计1393个文字,预计阅读时间需要6分钟。
目录前言编写代码实现PEP0690 建议的导入方法其一其二前言如果你的Python程序中有大量的import语句,且启动时非常缓慢,那么你应该尝试懒导入。
编写代码实现以下是一种实现懒导入的方法:
pythonimport importlib
def lazy_import(module_name, class_name): def get_class(): module=importlib.import_module(module_name) return getattr(module, class_name) return get_class
使用示例:
pythonMyClass=lazy_import('module_name', 'class_name')
PEP0690 建议的导入方法其一PEP0690 建议使用 `from ... import ...` 的形式进行导入,这样可以减少导入时的查找时间。
其二如果导入的模块很大,可以考虑将其为多个模块,或者使用 `from ... import ...` 形式导入所需的类或函数。
pythonfrom module_name import MyClass, my_function
前言如果你的Python程序中有大量的import语句,且启动时非常缓慢,那么你应该尝试懒导入。
本文共计1393个文字,预计阅读时间需要6分钟。
目录前言编写代码实现PEP0690 建议的导入方法其一其二前言如果你的Python程序中有大量的import语句,且启动时非常缓慢,那么你应该尝试懒导入。
编写代码实现以下是一种实现懒导入的方法:
pythonimport importlib
def lazy_import(module_name, class_name): def get_class(): module=importlib.import_module(module_name) return getattr(module, class_name) return get_class
使用示例:
pythonMyClass=lazy_import('module_name', 'class_name')
PEP0690 建议的导入方法其一PEP0690 建议使用 `from ... import ...` 的形式进行导入,这样可以减少导入时的查找时间。
其二如果导入的模块很大,可以考虑将其为多个模块,或者使用 `from ... import ...` 形式导入所需的类或函数。
pythonfrom module_name import MyClass, my_function
前言如果你的Python程序中有大量的import语句,且启动时非常缓慢,那么你应该尝试懒导入。

