if __name__ == '__main__' 如何正确理解

__name__ 是当前模块名,当模块被直接运行时模块名为 __main__ 。这句话的意思就是,当模块被直接运行时,以下代码块将被运行,当模块是被导入时,代码块不被运行。

__main__

'__main__' is the name of the scope in which top-level code executes. A module’s __name__ is set equal to '__main__' when read from standard input, a script, or from an interactive prompt.

A module can discover whether or not it is running in the main scope by checking its own __name__, which allows a common idiom for conditionally executing code in a module when it is run as a script or with python -m but not when it is imported:

if __name__ == "__main__":
    # execute only if run as a script
    main()

For a package, the same effect can be achieved by including a __main__.py module, the contents of which will be executed when the module is run with -m.

A module's __name__

Every module has a name and statements in a module can find out the name of its module. This is especially handy in one particular situation - As mentioned previously, when a module is imported for the first time, the main block in that module is run. What if we want to run the block only if the program was used by itself and not when it was imported from another module? This can be achieved using the __name__ attribute of the module.

Using a module's __name__

Example 8.2. Using a module's __name__

				
#!/usr/bin/python
# Filename: using_name.py

if __name__ == '__main__':
	print 'This program is being run by itself'
else:
	print 'I am being imported from another module'
				
				

Output

				
$ python using_name.py
This program is being run by itself

$ python
>>> import using_name
I am being imported from another module
>>>
				
				

How It Works

Every Python module has it's __name__ defined and if this is '__main__', it implies that the module is being run standalone by the user and we can do corresponding appropriate actions.

链接:https://www.zhihu.com/question/49136398/answer/114437881
# file one.py
def func():
    print("func() in one.py")

print("top-level in one.py")

if __name__ == "__main__":
    print("one.py is being run directly")
else:
    print("one.py is being imported into another module")

# file two.py
import one

print("top-level in two.py")
one.func()

if __name__ == "__main__":
    print("two.py is being run directly")
else:
    print("two.py is being imported into another module")

如果你执行one.py文件,

python one.py

会输出:

top-level in one.py
one.py is being run directly

如果你执行two.py文件,

python two.py

会输出:

top-level in one.py
one.py is being imported into another module
top-level in two.py
func() in one.py
two.py is being run directly

Thus, when module one gets loaded, its __name__ equals "one" instead of __main__.

最后,有这样的一句总结语形容的十分准确:if __name__ == '__main__' 编写私有化部分 ,这句代码以上的部分,可以被其它的调用,以下的部分只有这个文件自己可以看见,如果文件被调用了,其他人是无法看见私有化部分的





猜你喜欢

转载自blog.csdn.net/yu1150/article/details/80289007