程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Special variables for Python__ name__

編輯:Python

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 .

Examples and tests

We can do some examples and tests below .

Suppose we have the following 2 File .

ImportVarName.py

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")

VarName.py

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")

Operation results and interpretation

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


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved