python模块中的_all__属性,可用于模块导入时限制,如:from module import *此时被导入模块若定义了__all__属性,则只有__all__内指定的属性、方法、类可以导入。 若没定义,则导入模块内的所有公有属性,方法和类。
c.py
__all__ = ['test']
def test():
print("c-test")
def test1():
print("c-test1")
main.py
from c import *
test()
test1()
运行main.py打印结果如下:
c-test
Traceback (most recent call last):
File "D:/MyPython/main.py", line 4, in <module>
test1()
NameError: name 'test1' is not defined
本文介绍了Python中__all__属性的作用及使用方法。通过一个具体示例展示了当使用from module import *时,如何通过定义__all__来控制导入哪些成员。文章还包含了示例代码及其运行结果。
7707

被折叠的 条评论
为什么被折叠?



