下面是一个来自Dive Into Python书籍的一个例子,花了半天的时间才算彻底的明白这段代码,深感养家糊口不容易啊!
def info(object, spacing=10, collapse=1):
"""Print methods and doc strings.
Takes module, class, list, dictionary, or string."""
methodList = [e for e in dir(object) if callable(getattr(object, e))]
processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s)
print "\n".join(["%s %s" %
(method.ljust(spacing),
processFunc(str(getattr(object, method).__doc__)))
for method in methodList])
这个例子包含了映射List, 参数化字符串,连接与分割字符串的内容以及lambda函数的用法
1、映射List: 从ListA中读取数值,进行一些操作以后重新生成一个ListB.
methodList = [e for e in dir(object) if callable(getattr(object, e))]
dir(object) 返回的是object所有属性和方法名称,是一个List类型的值,我们通过映射List把这些方法一个一个取出来然后再经过if判断后赋值给methodList.
2、lambda & 连接与分割字符串:
processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s)
先看第一个点:代码 print 1 and "a" or "b" , 打印a
代码 print 0 and "a" or "b" , 打印b
通过上面的例子我们可以知道collapse是用来控制processFunc是使用 (lambda s: " ".join(s.split()))还是(lambda s: s)
再看第二个点:lambda,是当你想将一行代码做为一个函数使用的时候需要用到lambda。它返回的是函数的定义,语法是这样的lambda 参数1,参数2: 执行语句
最后一个点:" ".join(s.split()),
split具体参数定义这里就不解释了,大家可以通过__doc__来查看,s.split()这个函数就是根据空格字符串(1个或多个连续的空格)把s
字符串分割开来,并且会将所有的空格全部去掉返回一个List对象。"
".join(list)是将List中的元素通过空格重新连接起来形成一个string.
所以可以看出 collapse and (lambda s: " ".join(s.split())) or (lambda s: s)是通过collapse来控制是否需要调整输入的格式。
3、参数化字符串
["%s %s" % (method.ljust(spacing), processFunc(str(getattr(object, method).__doc__))) for method in methodList]
"%s %s" % (parm1,
parm2)是在字符串中加入两个str参数,%后面是参数的值。在给参数化字符串赋值多个参数的时候需要注意%后面必须是一个tuple类型的值,而不
能用List,因为List对象作为参数的时候会被转化为字符串识别成一个参数。
如:
l = ['a', 'b']
print "the string is : %s %s" % l
会提示“TypeError: not enough arguments for format string”的错误,因为l被认为是一个参数,字符串中需要两个str.
l = ['a', 'b']
print "the string is : %s" % l
打印的结果是:the string is : ['a', 'b']。
现在这个info()函数是干什么的应该一目了然了吧。info函数还是很实用的,可以帮我们查询object所有可用属性、函数的doc.