Python if _ _ name _ _ ==_ _ main _ _
一、简单理解:
对于模块中的程序代码分为:定义的变量、定义的函数,定义的类,还有其他一般语句(一般为了测试该模块的成员)。因为python是动态语言,当程序导入模块或直接运行时,该模块的顶层所有语句(包括一般语句)都被执行。
“Make a script both importable and executable”
脚本模块既自己可执行,导入到别的模块也可用。
# mymodu.py
modulenum = 8
def fun_p():
print("fun_P")
print("this is a module")
#只有一句导入语句
import mymodu
#执行结果
this is a module
怎么才模块导入时不执行不相关语句呢?
二、解决问题:
每个模块都有“name"属性,当模块被导入,该属性是模块名。如果直接执行默认为”main“.
若模块被调用,只需:
# mymodu.py
modulenum = 8
def fun_p():
print("fun_P")
if __name__ == "__main__":
print("this is a module")