《Dive into Python》读书笔记之内省的威力

Chapter 4: 内省的威力

info函数

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])

使用info函数

li = []
info(li)    # 打印li的各种方法的文档
import odbchelper
info(odbchelper)    #  打印odbchelper的文档
# 各种不同调用方法
info(odbchelper)
info(odbchelper, 12)
info(odbchelper, collapse=0) 
info(spacing=15, object=odbchelper)

使用 typestrdir 和其它内置函数

# type 查看对象类型
type(1)     # <type 'int'>
li = []
type(li)    # <type 'list'>
import odbchelper
type(odbchelper)    # <type 'module'>

# dir 查看对象属性
dir(li)
dir(odbchelper)

# callable 查看对象是否可调用
import string
string.punctuation  # '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
callable(string.punctuation)    # False
callable(string.join)   # True
print string.join.__doc__

# 查看内置函数
import __builtin__
dir(__buildin)

通过 getattr 获取对 象引用

li = ["Larry", "Curly"]
getattr(li, "append")("Lucy")   # 调用li的append方法,参数为"Lucy",相当于li.append("Lucy")
li                              # ["Larry", "Curly", "Lucy"]

andor的特殊性质

0''[](){}None 在布尔环境中为假;其它任何东西都为真。

# 有真有假返回假,两假返回前一个,两真返回后一个
# or相反
'' and 'a'      # ''
'' and []       # ''
'a' and ''      # ''
'a' and 'b'     # 'b'
使用and-or技巧

用表达式<exp> and a or b实现C语言中的bool ? a : b功能

a = "first"
b = "second"
1 and a or b    # "first"
0 and a or b    # "second"

此处a和b必须为真,否则会出错。

a = ""
b = "second"
1 and a or b    # "second", 应该为""

改进方法:使用(<exp> and [a] or [b])[0]保证a,b均为真。可在python无法使用if语句时使用, 如在lambda函数中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值