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)
使用 type
、str
、dir
和其它内置函数
# 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"]
and
和or
的特殊性质
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函数中。