O(1) 的小乐

Job Hunting

公告

记录我的生活和工作。。。
<2010年9月>
2930311234
567891011
12131415161718
19202122232425
262728293012
3456789

统计

  • 随笔 - 182
  • 文章 - 1
  • 评论 - 41
  • 引用 - 0

留言簿(10)

随笔分类(70)

随笔档案(182)

文章档案(1)

如影随形

搜索

  •  

最新随笔

最新评论

阅读排行榜

评论排行榜

What is `if __name__ == "__main__"` for?

转载自http://pyfaq.infogami.com/tutor-what-is-if-name-main-for

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.

posted on 2010-09-14 08:46 Sosi 阅读(209) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


统计系统