zoukankan      html  css  js  c++  java
  • if __name__ == '__main__'

    The simplest explanation for the __name__ variable (imho) is the following:

    Create the following files.

    # a.py
    import b
    
    # b.py
    print "Hello World from %s!" % __name__
    
    if __name__ == '__main__':
        print "Hello World again from %s!" % __name__
    

    Running them will get you this output:

    $ python a.py
    Hello World from b!
    

    As you can see, when a module is imported, Python sets globals()['__name__'] in this module to the module's name.

    $ python b.py
    Hello World from __main__!
    Hello World again from __main__!
    

    As you can see, when a file is executed, Python sets globals()['__name__'] in this file to __main__.

    之所以要有__name__ == '__main__'这个语句是因为:

    有时候我们需要 直接运行 一个模块,有时候我们需要 引入 一个模块而不是直接运行。加入这条语句,可以区别这个模板被直接运行和被引入两种下情况 不同执行效果

    first_module.py

    print ("First Module's Name: {}".format(__name__))
    

    输出结果:

    First Module's Name: main

    second_module.py

    import first_module
    
    print ("Second Module's Name: {}".format(__name__))
    
    

    输出结果:

    First Module's Name: first_module
    Second Module's Name: main

    如果 first_module.py

    def main():
        print ("First Module's Name: {}".format(__name__))
    
    if __name__ == '__main__':
        main()
    

    输出结果:

    First Module's Name: main

    这时如果 second_module.py

    import first_module
    
    print ("Second Module's Name: {}".format(__name__))
    

    输出结果:

    Second Module's Name: main

  • 相关阅读:
    从成本与职责谈测试的核心价值到底是什么
    浅谈测试媛职业发展
    Spotlight监控Oracle--Spotlight On Oracle安装和使用
    Jmeter-阶梯场景设置
    Jmeter-常用线程组设置及场景运行时间计算
    浮点数二分算法
    整数二分算法
    归并排序算法
    快速排序算法
    hadoop3.2+Centos7+5个节点主从模式配置
  • 原文地址:https://www.cnblogs.com/yaos/p/14014368.html
Copyright © 2011-2022 走看看