想象你写了一本书,你在封面上写上了书的名字(相当于模块的名字)。如果你是作者,你知道自己正在写这本书(相当于直接运行脚本),但如果有人拿着这本书读,他们会看到书名,而不是知道书是自己写的(相当于被导入为模块)。
def hello():
print("Hello from mymodule!")
if __name__ == "__main__":
# 只有在直接运行 mymodule.py 时,这部分代码才会执行
print("mymodule is being run directly")
hello()
else:
# 在 mymodule 被导入时,这部分代码不会执行
print("mymodule has been imported")
print('__name__ :', __name__)
mymodule has been imported
__name__ : mymodule
Hello from mymodule!
import mymodule
mymodule.hello()
mymodule has been imported
Hello from mymodule!