About the role and processing of ʻif name =='main':` described in the .py file.
-** When importing a file, do not execute the following if. ** **
By default, when you import a .py file, the contents of the file are executed.
ʻIf name =='main': `By writing below, you can avoid execution at the time of import.
Uses the property that the variable __name__
behaves differently when imported and when the file is executed.
「__name__」
-** If imported, it will be replaced with "module name" . - If the file is executed, it will be replaced with "main" **.
Only when the file is executed, the condition of the if statement becomes True, so the contents are executed.
test.py
print(__name__)
#output
__main__
How to write a file that is not output by import but is output by file execution.
module.py
def function name:
processing
if __name__ == "__main__":
Function name()
hello.py
def hello():
print("hello world")
if __name__ == "__main__":
hello()
--No output. -The module name "" hello "" is assigned to \ _ \ _ name \ _ \ _
$ python hello.py
--Output "hello world" -"\ _ \ _ Main \ _ \ _" is assigned to \ _ \ _ name \ _ \ _
Recommended Posts