Dive into python 实例学python (2) —— 自省,apihelper
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Dive into python 实例学python (2) —— 自省,apihelper,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2160字,纯文字阅读大概需要4分钟。
内容图文
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 forelement insource-list iffilter-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. """)
原文:http://www.cnblogs.com/549294286/p/3546568.html
内容总结
以上是互联网集市为您收集整理的Dive into python 实例学python (2) —— 自省,apihelper全部内容,希望文章能够帮你解决Dive into python 实例学python (2) —— 自省,apihelper所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。