In many Python When it comes to code , We may usually see __name__
This variable .
about Python This variable may not be very familiar to first-time users of .
It is good to understand in this way ,__name__
This variable is an identifier Python Global variables of the program .
We all know Python It's not main() Functional , If you are right about main Functions are not very familiar , You can make up your brain by yourself . Simply put, all programs need an entry when running ,main A function is the entry to a program , It is usually the entry after the program is started , All the programs are from main Function started .
__name__
Is a build to Python Variables in the interpreter , Used to identify the name of the currently running module .
This with Java Medium this.getClass().getName()
It's kind of similar .
We can do some examples and tests below .
Suppose we have the following 2 File .
This file is imported as a module . The source code of the file is as follows :
# -*- coding: utf-8 -*- # PPython __name__ module ImportVarName # Author - https://www.ossez.com print("ImportVarName __name__ = %s" % __name__) if __name__ == "__main__": print("ImportVarName is being run directly") else: print("ImportVarName is being imported")
This file can consider our main function file .
The source code of the file is as follows :
# -*- coding: utf-8 -*- # Python __name__ module Test # Author - https://www.ossez.com import ImportVarName print("Main VarName __name__ = %s" % __name__) if __name__ == "__main__": print("VarName is being run directly") else: print("VarName is being imported")
Some interpretations of the above running results are as follows .
If we run the source code directly :VarName.py, We will get the following output .
ImportVarName __name__ = ImportVarName ImportVarName is being imported Main VarName __name__ = __main__ VarName is being run directly Process finished with exit code 0
We can see that it is because we run from what we think is the main function , But before the main function runs , We imported the module ImportVarName, So in the module ImportVarName Medium __name__
The variable will be defined as the name of the module you import .
If you run the imported module directly ImportVarName Words , modular ImportVarName Medium __name__
It will be displayed as __main__
.
https://www.ossez.com/t/python-name/13393
stay Internet Todays rapid dev