Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1798336
  • 博文数量: 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-15 15:57:47

Chapter 4. The Power Of Introspection

This chapter covers one of Python's strengths: introspection. As you know, everything in Python is an object, and introspection is code looking at other modules and functions in memory as objects, getting information about them, and manipulating them. Along the way, you'll define functions with no name, call functions with arguments out of order, and reference functions whose names you don't even know ahead of time.

在这一章将介绍Python的一个亮点:内省(introspection).你知道,Python中所有的东西都是对象,而introspection是一个代码查找过程,它搜索内存中其它模块,函数对象,读取相关信息并能操纵它们。接下来将定义一个没有名字的函数,不安参数的顺序调用函数,引用一个事先不知道名字的函数。

4.1. Diving In

Here is a complete, working Python program. You should understand a good deal about it just by looking at it. The numbered lines illustrate concepts covered in Chapter 2,Your First Python Program. Don't worry if the rest of the code looks intimidating; you'll learn all about it throughout this chapter.

4.1 深入

这是一个完整独立的Python程序。在你读过以后,你要明白它的目的。带数字的行覆盖了第二章所介绍的概念。如果剩下的代码让你感到恐惧,不要紧张;在本章你将完全掌握它。

Example 4.1. apihelper.py

4.1apihelperl.py

If you have not already done so, you can  used in this book.

如果你还没有这么做(下载),你可以下载本例和本书例子的代码的代码

 

  1. def info(object, spacing=10, collapse=1):
  2.     """Print methods and doc strings.
  3.    
  4.     Takes module, class, list, dictionary, or string."""
  5.     methodList = [method for method in dir(object) if callable(getattr(object, method))]
  6.     processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s)
  7.     print "\n".join(["%s %s" %
  8.                       (method.ljust(spacing),
  9.                        processFunc(str(getattr(object, method).__doc__)))
  10.                      for method in methodList])
  11.  
  12. if __name__ == "__main__":
  13.     print info.__doc__

1

This module has one function, info. According to its function declaration, it takes three parameters: object, spacing, and collapse. The last two are actually optional parameters, as you'll see shortly.

这个模块包含一个函数,info。根据该函数的声明,它有三个参数,Object,spacing,collapse.稍后你将看到后面两个参数是可选的。

2

The info function has a multi-line doc string that succinctly describes the function's purpose. Note that no return value is mentioned; this function will be used solely for its effects, rather than its value.

函数info有一个多行的函数注释,函数注释有序的说明了函数的意图。注意这个函数没有提及返回值,这个函数在被调用时,仅仅使用他的作用,而不是该函数的返回值。

3

Code within the function is indented.

函数内的代码是缩进的。

4

The if __name__ trick allows this program do something useful when run by itself, without interfering with its use as a module for other programs. In this case, the program simply prints out the doc string of the info function.

If __name__ 技巧允许程序在自身运行时进行一些测试,而不影响该模块作为一个独立的模块时被其它模块调用。在本例中,程序仅仅是简单的打印出 函数的文档化注释。

5

if statements use == for comparison, and parentheses are not required.

If 语句使用 ==  进行比较,其中括号不是必须的。

The info function is designed to be used by you, the programmer, while working in the Python IDE. It takes any object that has functions or methods (like a module, which has functions, or a list, which has methods) and prints out the functions and their doc strings.

函数info 是为编程人员设计的,当他们使用pythonIDE时。它接受任何参数看,如含有函数或是方法的对象(比如模块办好对象,而列表包含方法)并打印出函数以及这些函数的文档化字符串。

Example 4.2. Sample Usage of apihelper.py

4.2 apihelper.py 的使用方法示例

  1. >>> from apihelper import info
  2. >>> li = []
  3. >>> info(li)
  4. append L.append(object) -- append object to end
  5. count L.count(value) -> integer -- return number of occurrences of value
  6. extend L.extend(list) -- extend list by appending list elements
  7. index L.index(value) -> integer -- return index of first occurrence of value
  8. insert L.insert(index, object) -- insert object before index
  9. pop L.pop([index]) -> item -- remove and return item at index (default last)
  10. remove L.remove(value) -- remove first occurrence of value
  11. reverse L.reverse() -- reverse *IN PLACE*
  12. sort L.sort([cmpfunc]) -- sort *IN PLACE*; if given, cmpfunc(x, y) -> -1, 0, 1

By default the output is formatted to be easy to read. Multi-line doc strings are collapsed into a single long line, but this option can be changed by specifying 0 for the collapseargument. If the function names are longer than 10 characters, you can specify a larger value for the spacing argument to make the output easier to read.

通常输出都被格式化成容易阅读的方式,多行的文档化注释都整理成单独一行,但是通过将选项collapse置为0,这个默认值可以被改变。如果函数名字长度超过了10,你可以将space参数设定一个更大的值以保证输出更易读。

Example 4.3. Advanced Usage of apihelper.py

4.3 apihelper.py的高级用法

  1. >>> import odbchelper
  2. >>> info(odbchelper)
  3. buildConnectionString Build a connection string from a dictionary Returns string.
  4. >>> info(odbchelper, 30)
  5. buildConnectionString Build a connection string from a dictionary Returns string.
  6. >>> info(odbchelper, 30, 0)
  7. buildConnectionString Build a connection string from a dictionary
  8.    
  9.     Returns string.

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