current position:Home>Python: simple about__ name__

Python: simple about__ name__

2022-02-02 14:14:55 Ice sky

Python When the module is introduced , The whole module will be executed . __name__ Is a system built-in variable , When we're in module1 When it's executed inside , At this point, the of this module __name__ The value is __main__

# module1
''' some code above, but will be ignored '''

# process here
if __name__ == '__main__':
    print('I am main')

When module1 Called as a module , For example, in module2 in , here __name__ The value of is the module name :

# module2
import module1

print(__name__) # '__main__'
print(module1.__name__) # '__module1__'

At this time due to Python When introducing modules , The whole module will be executed , At this time , In the original module module1 When the judgment statement is executed again in , At this time __name__ The value of is module1, It's not equal to __main__, Subsequent statements will not be executed at this time . therefore , We can go through Python This mechanism is judged in a module , When this module is executed , Whether it is imported into other modules for execution , Module can also be debug, Improve the robustness of the code .

copyright notice
author[Ice sky],Please bring the original link to reprint, thank you.

Random recommended