python 模块中的 __name__ 变量

python文件中,每一个python文件都可以看成一个模块。模块是对象,并且所有的模块都有一个内置属性 __name__。一个模块的 __name__ 的值取决于如何应用模块。

如果 import 一个模块,那么模块__name__ 的值通常为模块文件名,不带路径或者文件扩展名。若直接运行该py文件,则__name__ 的值将是一个特别缺省"__main__"。

例如:编写test.py文件  

if __name__ == '__main__':
    print('run the py file')
else:
    print('import by others')

若直接在ide中运行或者在命令行中运行python test.py,则输出  

run the py file
若在命令行下输入python,进入python运行环境后,输入import test,则会输出

import by others



你可能感兴趣的:(python)