Dive into python 实例学python (2) —— 自省,apihelper

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.
""")

 

转载于:https://www.cnblogs.com/549294286/p/3546568.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值