ʻIf \ _ \ _ name \ _ \ _ =='\ _ \ _ main \ _ \ _': ` I experienced how the output changes in 4steps + 2steps.
This time, I will show the behavior when executing .py indirectly with a tool such as "spyder" that is often used by beginners.
If you want to run "$ python XXX.py" directly in the terminal, please see the details from
__name__
print ('Hello!')
And save it as "hello.py".Example 1_hello.Define py
#hello.py
def function():
print('Hello!')
Example 2_hello.import py
import hello
hello.function()
#Output contents
#--------------------
# Hello!
#--------------------
↓ You can see that the function has been executed.
Example 3_add name
#hello.py
def function():
print('Hello!')
print(' __name__Then, what is displayed..!? -->' , __name__)
Example 4_hello.Try running py
import hello
hello.function()
#Output contents
#--------------------
#Hello!
#__name__Then, what is displayed..!? --> hello
#--------------------
↓ In the \ _ \ _ name \ _ \ _ part, "hello" of "hello.py" was displayed!
It turns out that \ _ \ _ name \ _ \ _ contains the module name 'hello'
of the imported module 'hello.py'
.
__main__
Example 1_Put "Sato" in the main.
#hello.py
def function(name):
print('Hello!',name)
print('By the way__name__The contents are-->',__name__)
if __name__ == '__main__':
print('Is the function in main executed?..?',function('Sato'))
Example 2_Display "Tanaka"
import hello
hello.function('Tanaka')
#Output contents
#--------------------
#Hello! Tanaka
#By the way__name__The contents are--> hello
#--------------------
↓
\ _ \ _ Name \ _ \ _ remained the module name 'hello'
of the module 'hello.py'
.
Therefore, the contents of ʻif name =='main':` (prepared "Sato") were not executed even though it was in function ().
I found that by setting ʻif name =='main': `, the following \ _ \ _ main \ _ \ _ is not executed.
Write the part that should not be executed when imported under ʻif name =='main': `.
reference [Python] if name == What is'main':?
Recommended Posts