应用模块的时候发现,只要导入一个模块中的函数,整个模块都会被执行
#suppose this is the_one.py
def fun_one():
print('this is 1file')
print('the module name is:',__name__)
def fun_two():
print('this is funtwo')
fun_two()
#suppose this is the_two.py
from the_one import fun_one
if __name__ == "__main__":
print('this is 2file')
print(__name__)
输出为:
this is funtwo
this is 2file
__main__
认识: 执行程序时,程序自动将当前程序命名为__mian__
if ‘__name__’ = '__main__'
的作用:当前程序既做模块,又可执行!
—————————————————————————————————————————
扩展:
以下部分参考:https://stackoverflow.com/questions/419163/what-does-if-name-main-do
程序一:
#suppose this is foo.py
print("before import")
import math
print("before functionA")
def functionA():
print("Function A")
print("before functionB")
def functionB():
print("Function B {}".format(math.sqrt(100)))
print("before __name__ guard")
if __name__ == '__main__':
functionA()
functionB()
print("after __name__ guard")
运行:
before import
before functionA
before functionB
before __name__ guard
Function A
Function B 10.0
after __name__ guard
程序二:
#suppose this is foo2.py
def functionA():
print("a1")
from foo2 import functionB
print("a2")
functionB()
print("a3")
def functionB():
print("b")
print("t1")
if __name__ == "__main__":
print("m1")
functionA()
print("m2")
print("t2")
运行:
t1
m1
a1
t1
t2
a2
b
a3
m2
t2