Python中if __name__ == '__main__'作用解析
当你打开一个.py文件时,经常会在代码的最下面看到if __name__ == '__main__':,现在就来介 绍一下它的作用.
模块是对象,并且所有的模块都有一个内置属性 __name__。一个模块的 __name__ 的值取决于您如何应用模块。如果 import 一个模块,那么模块__name__ 的值通常为模块文件名,不带路径或者文件扩展名。但是您也可以像一个标准的程序样直接运行模块,在这 种情况下, __name__ 的值将是一个特别缺省"__main__"。
///////////////////////////////////////////////////////////////////////////////////////////////////
在cmd 中直接运行.py文件,则__name__的值是'__main__';
而在import 一个.py文件后,__name__的值就不是'__main__'了;
从而用if __name__ == '__main__'来判断是否是在直接运行该.py文件
如:
#Test.py
class Test:
def __init(self):pass
def f(self):print 'Hello, World!'
if __name__ == '__main__':
Test().f()
#End
你在cmd中输入:
C:>python Test.py
Hello, World!
说明:"__name__ == '__main__'"是成立的
你再在cmd中输入:
C:>python
>>>import Test
>>>Test.__name__ #Test模块的__name__
'Test'
>>>__name__ #当前程序的__name__
'__main__'
无论怎样,Test.py中的"__name__ == '__main__'"都不会成立的!
所以,下一行代码永远不会运行到!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Many website developers face the problem of integrating Node.js or Python services under the LAMP architecture: the existing LAMP (Linux Apache MySQL PHP) architecture website needs...

When using Scapy crawler, the reason why pipeline persistent storage files cannot be written? Discussion When learning to use Scapy crawler for data crawler, you often encounter a...

Choice of Python Cross-platform desktop application development library Many Python developers want to develop desktop applications that can run on both Windows and Linux systems...

Python process pool handles concurrent TCP requests that cause client to get stuck. When using Python for network programming, it is crucial to efficiently handle concurrent TCP requests. ...

Deeply explore the viewing method of Python functools.partial object in functools.partial using Python...

Getting started with Python: Hourglass Graphic Drawing and Input Verification This article will solve the variable definition problem encountered by a Python novice in the hourglass Graphic Drawing Program. Code...

How to handle high resolution images in Python to find white areas? Processing a high-resolution picture of 9000x7000 pixels, how to accurately find two of the picture...

Data Conversion and Statistics: Efficient Processing of Large Data Sets This article will introduce in detail how to convert a data list containing product information to another containing...
