zoukankan      html  css  js  c++  java
  • Python中if __name__ == "__main__": 的作用 (整理转自Arkenstone) --感谢!

    Python中if __name__ == "__main__": 的作用

    在很多python脚本中在最后的部分会执行一个判断语句if __name__ == "__main__:",之后还可能会有一些执行语句。那添加这个判断的目的何在?

    在python编译器读取源文件的时候会执行它找到的所有代码,而在执行之前会根据当前运行的模块是否为主程序而定义变量__name__的值为__main__还是模块名。因此,该判断语句为真的时候,说明当前运行的脚本为主程序,而非主程序所引用的一个模块。这在当你想要运行一些只有在将模块当做程序运行时而非当做模块引用时才执行的命令,只要将它们放到if __name__ == "__main__:"判断语句之后就可以了。

    具体举个栗子方便理解:

    # file one.py
    def func():
        print("func() in one.py")
    
    print("top-level in one.py")
    
    if __name__ == "__main__":
        print("one.py is being run directly")
    else:
        print("one.py is being imported into another module")
    # file two.py
    import one        # start executing one.py
    
    print("top-level in two.py")
    one.func()
    
    if __name__ == "__main__":
        print("two.py is being run directly")
    else:
        print("two.py is being imported into another module")

    运行 python one.py输出如下:

    top-level in one.py
    one.py is being run directly

    运行python two.py 输出如下:

    zjf@zjf-MATE:~/test$ python3 two.py
    top-level in one.py
    one.py is being imported into another module
    top-level in two.py
    func() in one.py
    two.py is being run directly
  • 相关阅读:
    LA 3026 Period
    Touch
    Uva 11762 Race to 1
    清北学堂模拟赛d1t2 火柴棒 (stick)
    清北学堂模拟赛d1t1 位运算1(bit)
    常州模拟赛d8t2 绘画
    常州模拟赛d8t1 友好数对
    常州模拟赛d5t3 appoint
    常州模拟赛d7t1 亲戚
    常州模拟赛d7t3 水管
  • 原文地址:https://www.cnblogs.com/santizhou/p/7639554.html
Copyright © 2011-2022 走看看