之前遇到的python中"if _name_ == ‘_main_‘:",一直感觉理解的不透彻,今天在写代码的时候突然想明白了,赶紧记下来,好记性不如烂笔(jian)头(pan)嘛。
我的理解是,这句话就是一个最简单的 if 判断语句。
首先我们来解释一下这句话,_name_指的是当前模块名,一般来说,模块名就是文件名(不包括扩展名哦),而模块被直接运行的时候,模块名就不再是文件名了,而是_main_了,所以这句话翻译过来就是,当模块直接被运行时,
"if _name_ == ‘_main_‘:"这句话下面的代码块将被执行,相反,如果模块是被导入进来的,代码块就不会被执行。
举个栗子:
# test_1.py
def func_1():
print('func_1 is invoked')
print('This is test_1')
if __name__ == '__main__':
print('test_1.py is executed directly')
else:
print('test_1.py is imported')
# test_2.py
import test_1
print('This is test_2')
test_1.func_1()
if __name__ == '__main__':
print('test_2.py is executed directly')
else:
print('test_2.py is imported ')
如果执行test_1.py,输出的结果为:
This is test_1
test_1.py is executed directly
如果执行test_2.py,输出的结果为:
This is test_1
test_1.py is imported
This is test_2
func_1 is invoked
test_2.py is executed directly
有些小伙伴儿可能会对 test_2.py 的执行结果有疑惑,在这里我解释一下,对于被导入的模块来说,模块中的函数是调用时才执行的,但是语句部分就会立即执行,就是那些没有缩进的,比如 print 啊,变量赋值等等,所以导入 test_1 时候,test_1中的 print 语句会执行,然后 if 判断语句执行else的部分。不过我们使用
"if _name_ == ‘_main_‘:"的时候,往往把else部分直接省略了而已。
主要内容就是这样,欢迎小伙伴儿们拍砖交流,多多指教啦~