apihelper.py
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]) if __name__ == "__main__": print help.__doc__
1、可选参数和命名参数
2、内置函数
type(obj)返回obj的数据类型
str(data)将数据强制转化为字符串
dir(obj)返回obj的属性和方法列表
callable(c)测试c是否可以调用
3、getattr()获取对象的引用
4、过滤列表
[mapping-expression for element in source-list if filter-expression]
5、and 和 or
and返回第一个假值,如果都为真,返回最后一个真值。
or返回第一个真值,如果都为假,返回最后一个假值。
>>> a = "first" >>> b = "second" >>> 1 and a or b 1 ‘first‘ >>> 0 and a or b 2 ‘second‘
类似于: bool ? a : b
安全使用:
>>> a = "" >>> b = "second" >>> (1 and [a] or [b])[0] 1
6、lambda表达式
测试代码
import unittest import apihelper import sys from StringIO import StringIO class Redirector(unittest.TestCase): def setUp(self): self.savestdout = sys.stdout self.redirect = StringIO() sys.stdout = self.redirect def tearDown(self): sys.stdout = self.savestdout class KnownValues(Redirector): def testApiHelper(self): """info should return known result for apihelper""" apihelper.info(apihelper) self.redirect.seek(0) self.assertEqual(self.redirect.read(), """info Print methods and doc strings. Takes module, class, list, dictionary, or string. """) class ParamChecks(Redirector): def testSpacing(self): """info should honor spacing argument""" apihelper.info(apihelper, spacing=20) self.redirect.seek(0) self.assertEqual(self.redirect.read(), """info Print methods and doc strings. Takes module, class, list, dictionary, or string. """) def testCollapse(self): """info should honor collapse argument""" apihelper.info(apihelper, collapse=0) self.redirect.seek(0) self.assertEqual(self.redirect.read(), """info Print methods and doc strings. Takes module, class, list, dictionary, or string. """)