在Python中,__all__
通常用于定义模块的公开接口。在使用from module import *
语句时,此时被导入模块若定义了__all__属性,则只有__all__内指定的属性、方法、类可被导入;若没定义,则导入模块内的所有公有属性,方法和类。这可以帮助开发者明确地指定哪些符号是模块的公共API,以防止不必要的符号被导入。
以下是__all__
的用法示例:
module.py
# module.pydef public_function():return "This is a public function."def _private_function():return "This is a private function."variable = "This is a variable."__all__ = ['public_function', 'variable']
在上面的示例中,public_function
和variable
被列在__all__
列表中,表示它们是该模块的公开接口。_private_function
没有包含在__all__
中,因此它被视为私有函数,不会在使用from module import *
语句时被导入。
在使用from module import *
导入模块时,只有在__all__
列表中列出的符号会被导入。如果没有定义__all__
,默认行为是导入所有不以下划线开头的全局符号。
# test.pyfrom module import *def test():print(public_function())print(variable)print(_private_function())test()
运行
参考:
python __all__ 用法_刘金宝_Arvin的博客-CSDN博客
本文发布于:2024-02-02 07:49:49,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170683138842387.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |