1. 程式人生 > >Python之:if __name__ == "__main__":

Python之:if __name__ == "__main__":

五句話搞清楚關係,對前輩們佩服

阿凱.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

如有錯誤,歡迎指正!