关于_ _name_ _的说明

_ _name_ _是一个内置变量,当运行程序自己的是时候,变量值为_ _main_ _;当被其他程序当作模块导入时,值为文件名;这个一般被配合if else语句使用;写在程序最下面,函数定义,变量定义写在最上面。由于python是解释性脚本程序,依据从上到下执行,由以上的做法巧合的让python出现主函数入口,且可屏蔽被导入模块里边的主函数运行,即,另一个程序里边的函数只能被调用。例如:

# file green.py
def fun():
    print("fun() in green.py")
if __name__ == "__main__":
    print("green.py is being run directly")
else:
    print("green.py is being imported into another module")

# file bule.py
import green
green.fun()
if __name__ == "__main__":
    print("bule.py is being run directly")
else:
    print("bule.py is being imported into another module")
如果你执行green.py文件,python green.py
输出:green.py is being run directly

如果你执行bule.py文件,python bule.py
输出:green.py is being imported into another module
              fun() in green.py
              bule.py is being run directly

猜你喜欢

转载自blog.csdn.net/chanleoo/article/details/80965929