python中的每个模块都有一个称为
名称
. 价值
名称
属性为'
主要的
'当模块直接运行时。否则
名称
是模块的名称。
简而言之就是一个小例子。
#Script test.py
apple = 42
def hello_world():
print("I am inside hello_world")
if __name__ == "__main__":
print("Value of __name__ is: ", __name__)
print("Going to call hello_world")
hello_world()
我们可以直接执行
python test.py
输出
Value of __name__ is: __main__
Going to call hello_world
I am inside hello_world
现在假设我们从其他脚本调用上面的脚本
#script external_calling.py
import test
print(test.apple)
test.hello_world()
print(test.__name__)
当你执行这个
python external_calling.py
输出
42
I am inside hello_world
test
因此,上面的内容不言而喻,当您从其他脚本调用test时,if循环
名称
在test.py中将不执行。