Why do you need to use "if __name__ =='__main__'" statement in python

First, use the most concise language to explain the function of if __name__ =='__main__':: to prevent the display of redundant program main parts when imported by other files .

 

Let me give you an example, what happens if you don't use if __name__ =='__main__'::

First call cs.py in yy.py

#yy.py
import cs
print('引用cs')
cs.cs()
print('程序结束!')

The cs.py file is as follows

#cs.py
def cs():
    print('一打开cs!')
 
print('cs主函数!')

The result of the operation will be:

cs主函数!
引用cs
一打开cs!
程序结束!

Analysis: In other words, if your purpose is only to call the cs() function in cs.py, then you should not use import cs when importing

Because once you use import cs 

Then cs.py will be automatically run once when the import code is run to this sentence. The functions in cs.py are encapsulated and will not be run directly, but there are statements in cs.py that are not encapsulated:

print('cs主函数!')

Therefore, this sentence will be run redundantly, even if you do not need this sentence at all, your purpose is just to call the cs() function in cs.py

Even use 

from cs import cs

The results are still the same.

So how can we avoid running unnecessary code segments? Then take the unnecessary code segment as a function to run, but this function is a bit special, he has to distinguish whether it is running by itself or being imported and run by itself. If it is running by itself, then those code segments will be displayed, and if it is called, it will be blocked. Drop.

So if __name__ =='__main__': came into being

Let's modify the code

Just modify the code of cs.py:

def cs():
    print('已打开cs!')
 
if __name__ == '__main__':
    print('cs主函数!')

Then run yy.py

The results are as follows:

引用cs
已打开cs!
程序结束!

 

At this point, everyone should know what if __name__ =='__main__': is for!

 

 

First, use the most concise language to explain the function of if __name__ =='__main__':: to prevent the display of redundant program main parts when imported by other files .

 

Let me give you an example, what happens if you don't use if __name__ =='__main__'::

First call cs.py in yy.py

Guess you like

Origin blog.csdn.net/m0_54162026/article/details/112858459