python程序的运行顺序`if ‘__name__’ = '__main__'

应用模块的时候发现,只要导入一个模块中的函数,整个模块都会被执行

#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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值