Python 关于 name main的使用

本文详细解析了Python中__name__属性的作用及其应用场景。通过一个具体的例子展示了如何利用if __name__ == '__main__':来区分文件作为主程序运行还是被其他文件导入时的行为差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

__name__:

在使用自身的时候,就是main,比如你执行:
python test.py
此时在test.py里面的name就是main
如果你在test2中import test,那么name就是文件名

http://www.cnblogs.com/herbert/archive/2011/09/27/2193482.html

看过很多python的code都有这段代码:

if __name__ == '__main__':
这段代码的主要作用主要是让该python文件既可以独立运行,也可以当做模块导入到其他文件。当导入到其他的脚本文件的时候,该main代码里面的就不执行了。
参考:
http://pyfaq.infogami.com/tutor-what-is-if-name-main-for
 

The if __name__ == "__main__": ... trick exists in Python so that our Python files can act as either reusable modules, or as standalone programs. As a toy example, let's say that we have two files:

mumak:~ dyoo$ cat mymath.py
def square(x):
    return x * x

if __name__ == '__main__':
    print "test: square(42) ==", square(42)


mumak:~ dyoo$ cat mygame.py
import mymath

print "this is mygame."
print mymath.square(17)

In this example, we've written mymath.py to be both used as a utility module, as well as a standalone program. We can run mymath standalone by doing this:

mumak:~ dyoo$ python mymath.py
test: square(42) == 1764

But we can also use mymath.py as a module; let's see what happens when we run mygame.py:

mumak:~ dyoo$ python mygame.py
this is mygame.
289

Notice that here we don't see the 'test' line that mymath.py had near the bottom of its code. That's because, in this context, mymath is not the main program. That's what the if __name__ == "__main__": ... trick is used for.

 

在这个例子里面mygame.py里面调用square函数的时候,就不会执行mymath.py里面的main函数了。

转载于:https://my.oschina.net/sincoder/blog/67754

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值