五句话搞清楚关系,对前辈们佩服
阿凯.py
朋友眼中你是阿凯(__name__ == "阿凯")
你自己眼中你是你自己(__name__ == "__main__")
你编程很好,朋友阿黄调你去帮他写程序(import 阿凯, 这时你在朋友眼中:__name__ == "阿凯")
但你晚上也会打开XX网站,做一些自己的事情(直接运行阿凯.py,__name__ == "__main__")
示例如下:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#file one.py
def func():
print("func() is one.py")
print("top-level in one.py")
if __name__ == "__main__":
print("one.py is being run directly")
else:
print("one.py is being imported into another module")
#直接运行one.py,结果如下:
#top-level in one.py
#one.py is being run directly
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#file two.py
import one
print("top-level in two.py")
one.func()
if __name__ == "__main__":
print("two.py is being run directly")
else:
print("two.py is being imported into another module")
#运行two.py,结果如下:
#top-level in one.py
#one.py is being imported into another module
#top-level in two.py
#func() is one.py
#two.py is being run directly
如有错误,欢迎指正!