Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1752514
  • 博文数量: 335
  • 博客积分: 4690
  • 博客等级: 上校
  • 技术积分: 4341
  • 用 户 组: 普通用户
  • 注册时间: 2010-05-08 21:38
个人简介

无聊之人--除了技术,还是技术,你懂得

文章分类

全部博文(335)

文章存档

2016年(29)

2015年(18)

2014年(7)

2013年(86)

2012年(90)

2011年(105)

分类: Python/Ruby

2011-06-13 00:26:52

2.6. Testing Modules

模块测试

Python modules are objects and have several useful attributes. You can use this to easily test your modules as you write them. Here's an example that uses the if __name__ trick.

所有的Python模块都是对象,它们有些很常用的属性。当你在写模块的时候,使用这些属性会使你很轻松的测试这些模块。下面给出一个包含魔术的  if __name__ 属性的例子

 

  1. if __name__ == "__main__":

Some quick observations before you get to the good stuff. First, parentheses are not required around the if expression. Second, the if statement ends with a colon, and is followed by indented code.

在继续阅读下面内容之前,请先快速的观察一下。首先 if表达式本身不需要括号。其次 if语句使用冒号来结束,后面跟缩进代码。

 

Like C, Python uses == for comparison and = for assignment. Unlike C, Python does not support in-line assignment, so there's no chance of accidentally assigning the value you thought you were comparing.C一样,Python使用 == 来进行比较两个对象,使用=来进行赋值。与C不同的是,Python不支持行内赋值,因此不会存在这种偶然的可能:在赋值的时候,你认为你在进行逻辑比较(???)

 


So why is this particular
 if statement a trick? Modules are objects, and all modules have a built-in attribute __name__. A module's __name__ depends on how you're using the module. If you import the module, then __name__ is the module's filename, without a directory path or file extension. But you can also run the module directly as a standalone program, in which case __name__ will be a special default value, __main__.

但是这为什么说if __name__  有魔术呢?模块都是对象,所有的模块都有一个内置属性:__name__。模块的__name__属性依赖你正在使用的模块。如果你导入了一个模块,那么__name__就是该模块的文件名,而不包括目录路径或是文件扩展名。但是你也可以将一个模块直接作为一个独立的程序来运行,在这种情况下,__name__的值将是 __main__.

  1. >>> import odbchelper
  2. >>> odbchelper.__name__
  3. 'odbchelper'

Knowing this, you can design a test suite for your module within the module itself by putting it in this if statement. When you run the module directly, __name__ is __main__, so the test suite executes. When you import the module, __name__ is something else, so the test suite is ignored. This makes it easier to develop and debug new modules before integrating them into a larger program.

知道这点,你就可以对你的模块,设计一个单元测试包。在模块内部放置上面的if语句。如果你直接运行该模块,__name__ 属性值为 __main__,那么这个测试抱执行。当你导入该模块时,__name__ 为其他值,测试包被忽略掉。这样使得在将一个新的模块集成一个更大的程序时,开发和测试更加容易。

Tip

 

On MacPython, there is an additional step to make the if __name__ trick work. Pop up the module's options menu by clicking the black triangle in the upper-right corner of the window, and make sure Run as __main__ is checked.MacPython上为了是 if __name__ 生效,你需要进行额外的操作。点击窗口右上角的黑三角,弹出模块选项菜单,确定 run as __main__  被选中。

 

 

阅读(922) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~