Python study notes: if __name__ == '__main__'

#The learning content comes from Liao Xuefeng's python learning tutorial discussion area

About the code if __name__ == '__main__': Here are a few examples to explain:

First write a test module add1.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

' a test module '

def addFunc(a,b):  
    return a+b  

print('add1计算结果:',addFunc(1,1))

Write another module add2.py to call the above module:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

' a test module '

import add1

print('调用add1模块执行的结果是:',add1.addFunc(12,23))

Open cmd in the path of the two modules just now (my path is: "C:\work"), and run add1.py with the command line:

C:\work>python add1.py
add1计算结果: 2

Open in the paths of the two modules just now and run add2.py from the command line:

C:\work>python add2.py
add2计算结果: 2
调用test模块执行的结果是: 35

#显然,当我运行add2.py后第一句并不是调用者所需要的,为了解决这一问题,Python提供了一个系统变量:__name__

#注:name两边各有2个下划线__name__有2个取值:当模块是被调用执行的,取值为模块的名字;当模块是直接执行的,则该变量取值为:__main__

Therefore, the test code of the called module can be written in the if statement, as follows:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

' a test module '

def addFunc(a,b):  
    return a+b  

if __name__ == '__main__':  
    print('add1计算结果:',addFunc(1,1))

When running add1.py again:

C:\work>python add1.py
add1计算结果: 2

#结果并没有改变,因为调用add1.py时,__name__取值为__main__,if判断为真,所以就输出上面的结果

When running add2.py again:

C:\work>python add2.py
调用test模块执行的结果是: 35

#此时我们就得到了预期结果,不输出多余的结果。能实现这一点的主要原因在于当调用一个module时,此时的__name__取值为模块的名字,所以if判断为假,不执行后续代码。

So the code iif __name__ == '__main__': realizes the function of Make a script both importable and executable , which means that the module can be imported into other modules for use, and the module itself can also be executable.

 

       If you have learned the C language, you can know that the main program entry defined by the C language is the main() function, and main represents the main entry of the program, that is, the interface with the system (in other words, the command line is called directly). if name == ' main ': The core of this sentence is nothing more than judging whether the program file is used as the main program entry. If the program file is called directly on the command line, the file is used as the main program entry, and name == ' main ' of course. If you call other program files on the command line, the main program entry name == ' main ' naturally does not hold, because main is equal to the program name you entered on the command line. The advantage of this thing is that when others call it (you are not the main program entry), the things behind it do not run, and when your own command line is executed (you are the main program entry), the things behind it run. So it can be used as a test.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324974098&siteId=291194637