Dive into Python读书笔记1

python也敲了有一段时间了,发现该深入学习下了。先从Dive into Python 开始吧。

老样子,我不会照搬课本的内容,主要挑一些有收获的。

1.__doc__

python 里面一切皆对象,对象object的说明可以通过object.__doc__ 来查看

例如:print [].__doc__

list() -> new empty list
list(iterable) -> new list initialized from iterable's items

ps,为了让别人可以查看你的模块或函数信息,请不要忘了 写自己的注释哦

2.dir 与 getattr

dir(object) 会返回一个list,这个list包含了这个对象所有属性与方法的名称。

例如:dir([])

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

getattr(object, attribute) 返回对象里名为attribute的属性或方法的一个引用。当object不存在attribute时,getattr会抛出一个异常。我们可以为getattr添加一个返回的默认值比如

getattr(object, attribute, None) 这样当找不到时,就返回一个None

例如:getattr([], 'append').__doc__

'L.append(object) -- append object to end'

例如:a=[]     fun=getattr(a,'append')  fun(1)  a

[1]

__doc__,dir ,getattr 结合起来用,可以帮你打开探索python之门

留个小任务,用这三个 探索下 __builtins__ 吧,你会有惊喜哦

3.可以使代码更简洁的一些语法特性

 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 = [e for e in dir(object) if callable(getattr(object, e))]
 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 help.__doc__
原文地址:https://www.cnblogs.com/2010Freeze/p/2969923.html