Python——系统变量__name__

  • 系统变量__ name __ 是用标识模块的名字的一个系统变量。

  • 这里分两种情况:
    假如当前模块是主模块(也就是调用其他模块的模块),那么此模块名字就是__main__,通过if判断这样就可以执行“mian:”后面的主函数内容;
    假如此模块是被import的,则此模块名字为文件名字(不加后面的.py),通过if判断这样就会跳过“__ mian __:”后面的内容。

  • 举个例子:
    1.定义第一个file1.py,运行该文件后,会执行testA函数

def testA(a,b):
	print(a+b)
print(__name__)
if __name__ == '__main__':
	testA(1,1)
	
# when you run this file,the results are as follows
'__main__'
2
	

2.再定义一个file2.py文件,这次不会运行testA,因为标识file1的系统变量不为__ mian __了

import file1

print(__name__)
# when you run this file,the results are as follows:

'file1' # run file1 print() function
'__main__'

猜你喜欢

转载自blog.csdn.net/weixin_44441131/article/details/107324768