Two uses python file

Two uses python file

One, two purposes

Before talking about the knowledge we are speaking about the first two python files

Executable file : file currently running

Module file : imported file

eg:

from m1 import y  #m1为模块文件
print(y)

Execute files and modules file is relative

So his two uses are:

  1. script. The entire file is a program used to be executed
  2. Module. Files stored in pile function, used to be introduced

Second, Talkingif __name__ == '__main__':

Before we look at a code, which exists m.py file

#m.py


x =1

def f1():
    print(m)
    
def f2():
    print(n)
    
    
if __name__ == '__main__':
    
    
f1()
f2()

Next is the implementation of a file run.py

# run.py

import m

If you run directly run.py will run directly m.py in f1()and f2(), but if we add in aaa.py in if __name__ == '__main__':this sentence, you can prevent run run.py execution f1()and f2().

When m.pytime is treated as executable file __name__ == '__main__';

In the m.pytime being as the module files __name__ == 'm'.

It can make m.py have different usage under different scenarios.
if __name__ == '__main__':It is actually a ifjudgment, or a filter.

Guess you like

Origin www.cnblogs.com/yanjiayi098-001/p/11360207.html