Python小白学习之路(二十六)—【if __name__ =='__main__':】【用状态标识操作】

规则一:

一个python文件中,只写一些可以运行的功能
测试代码写在这句代码下面

if __name__ =='__main__':

在讲这边的时候,我不是很懂
参考了一篇博客,地址如下:
http://blog.konghy.cn/2017/04/24/python-entry-program/

简单来理解,可以把    if __name__ =='__main__':     理解为python程序的入口

对于很多编程语言来说,程序都必须要有一个入口,比如 C,C++,以及完全面向对象的编程语言 Java等。

如果你接触过这些语言,对于程序入口这个概念应该很好理解,C 和 C++ 都需要有一个 main 函数来作为程序的入口,

也就是程序的运行会从 main 函数开始。同样,Java 必须要有一个包含 Main 方法的主类来作为程序入口。

而 Python 则有不同,它属于脚本语言,不像编译型语言那样先将程序编译成二进制再运行,而是动态的逐行解释运行。

也就是从脚本第一行开始运行,没有统一的入口。

一个 Python 源码文件除了可以被直接运行外,还可以作为模块(也就是库)被导入。

不管是导入还是直接运行,最顶层的代码都会被运行(Python 用缩进来区分代码层次)。

而实际上在导入的时候,有一部分代码我们是不希望被运行的。

#举一个例子来说明一下,假设我们有一个 const.py 文件,内容如下:

PI = 3.14
def Math():
    print('PI = %s'%PI)
Math()

我们在这个文件里边定义了一些常量,然后又写了一个 Math 函数来输出定义的常量,

最后运行 Math 函数就相当于对定义做一遍人工检查,看看值设置的都对不对。

然后我们直接执行该文件(python const.py),输出:

PI = 3.14

现在,我们有一个 area.py 文件,用于计算圆的面积,

该文件里边需要用到 test.py 文件中的 PI 变量,那么我们从 const.py 中把 PI 变量导入到 test.py 中:

from const import PI
def calc_round_area(radius):
    return PI *(radius**2)
def calc():
    print('round area = %s'%(calc_round_area(2)))
calc()

运行test.py ,输出结果

PI = 3.14
round area = 12.56

可以看到,const 中的 Math 函数也被运行了,实际上我们是不希望它被运行,

提供 Math 也只是为了对常量定义进行下测试。

这时,if __name__ == '__main__' 就派上了用场。把 const.py 改一下:

PI = 3.14
def Math():
    print('PI = %s'%PI)
if __name__ == '__main__':
    Math()


然后再运行 test.py,输出如下:

round area = 12.56

总结:


if __name__ =='__main__':

就相当于是 Python 模拟的程序入口。

Python 本身并没有规定这么写,这只是一种编码习惯。

由于模块之间相互引用,不同模块可能都有这样的定义,而入口程序只能有一个。

到底哪个入口程序被选中,这取决于__name__的名字。
(先理解到这边)

规则二:

在编程中,利用一个状态来标识某种操作

举例:

有一个三层嵌套的循环程序,我可以通过break来跳出当前层的循环,
实现每一层之间进行切换。如果我现在在最里层,我要求一步切换到最外层
通过break来跳出,需要跳三次。

while True:
    print('leve11')
    choice = input('levell:').strip()
    if choice == 'quit':break
    while True:
        print('level2')
        choice = input('level2:').strip()
        if choice == 'quit': break
        while True:
            print('level3')
            choice = input('level3:').strip()
            if choice == 'quit': break
            

如果利用 tag 的状态来标识这种操作,可以实现循环最里层到最外层一步跳跃。

tag = True
while tag:
    print('leve11')
    choice = input('levell:').strip()
    if choice == 'quit':break
    if choice == 'quit all': tag = False
    while tag:
        print('level2')
        choice = input('level2:').strip()
        if choice == 'quit': break
        if choice == 'quit all': tag = False
        while tag:
            print('level3')
            choice = input('level3:').strip()
            if choice == 'quit': break
            if choice == 'quit all':tag = False
原文地址:https://www.cnblogs.com/guoruxin/p/10109621.html