Dive into Python 每一章节都以一个例子开始,这个例子基本上贯穿了这个章节所要讲解的知识点,还使用了上一章节所讲的知识点,这样的例子对初学者来说却是不错。
apihelper.py
def info(object, spacing=10, collapse=1):
"""Print methods and doc strings.
Takes module, class, list, dictionay, or string"""
methodList = [method for method in dir(object) if callable(getattr(object,method))]
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])
if __name__ == "__main__":
print info.__doc__
1. Default value
这个例子中的function里面有三个参数,后两个都有default value,这个和C++的function很相似,不过还是有不同的地方,Python里,调用这个function,参数的位置不一定是这个顺序,比如,你可以这么调用 info(spacing=30, object=apihelper)
2.and & or
这个通过三个小例子还说明
>>>a=”first”
>>>b=”second”
>>>1 and a or b
‘first’
>>>0 and a or b
‘second’
>>>a=””
>>>b=”second”
>>>1 and a or b
‘second’
>>>a=””
>>>b=”second”
>>>(1 and [a] or [b])[0]
‘’
书上的原文(红色字体的片断均来自书上)
When using and, values are evaluated in a boolean context from left to right. 0, '', [], (), {}, and None are false in a boolean context; everything else is true. Well, almost everything. By default, instances of classes are true in a boolean context, but you can define special methods in your class to make an instance evaluate to false.
3.Filtering Lists
[method for method in dir(object) if callable(getattr(object,method))]
关键词都加粗了
关键要认准格式
4.dir & getattr
dir returns a list of the attributes and methods of any object: modules, functions, strings, lists, dictionaries... pretty much anything.
getattr returns a reference to a function(method) of any object: modules, strings, lists, dictionaries… pretty much anything.
(我照着上面写的n_n,加粗的地方就是getattr的参数)
5.Callable
the callable function takes any object and returns True if the object can be called, or False otherwise.
6.lambda s
这是一个“简化”的function!格式是: lambda s: expression of s
它的返回值是expression of s 的结果。
可以把它assign给一个变量,如: g = lambda s: s.split(),则g是一个以s为参数的函数。
7.str
str把非string类型的类型变成string类型,比如:
1 -> ‘ 1’
[ ] -> “[ ]”
None -> ‘None’
例子中之所以要用到str,是因为有些function的 doc string 可能没有,则返回None。
显示中用 %s ,则表明一定要为string类型的,用str做下装饰,遇到None也不怕了!
明白这些后,例子是不是也很容易理解了?