程序员文章、书籍推荐和程序员创业信息与资源分享平台

网站首页 > 技术文章 正文

【python编程】__all__关键字的作用

hfteth 2024-12-26 13:45:24 技术文章 15 ℃

python模块中的__all__用于模块导入时限制。被导入模块若定义了__all__属性,则只有在__all__内指定的属性、方法、类可被导入;若没定义,则导入模块内的所有公有属性,方法和类。比如下面的代码

# mymodule.py
__all__ = ['imported_by_star']
imported_by_star = 42
not_imported_by_star = 21

当使用from mymodule import *时,只有在__all__变量里的符号才会被导入

>>> from mymodule import *
>>> imported_by_star
42
>>> not_imported_by_star
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'not_imported_by_star' is not defined

也可以显式地导入其它的符号 not_imported_by_star

>>> from mymodule import not_imported_by_star
>>> not_imported_by_star
21

最近发表
标签列表