学习Python知识小结 杂记二

Dive into Python 每一章节都以一个例子开始,这个例子基本上贯穿了这个章节所要讲解的知识点,还使用了上一章节所讲的知识点,这样的例子对初学者来说却是不错。

 

apihelper.py

def info(object, spacing=10, collapse=1):

    """Print methods and doc strings.

    Takes module, class, list, dictionay, or string"""

    methodList = [method for method in dir(object) if callable(getattr(object,method))]

    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 info.__doc__

                           

 

1.    Default value

这个例子中的function里面有三个参数,后两个都有default value,这个和C++function很相似,不过还是有不同的地方,Python里,调用这个function,参数的位置不一定是这个顺序,比如,你可以这么调用 info(spacing=30, object=apihelper)

 

2and & or

这个通过三个小例子还说明

>>>a=”first”

>>>b=”second”

>>>1 and a or b

‘first’

>>>0 and a or b

‘second’

 

>>>a=””

>>>b=”second”

>>>1 and a or b

‘second’

 

>>>a=””

>>>b=”second”

>>>(1 and [a] or [b])[0]

‘’

 

书上的原文(红色字体的片断均来自书上)

When using and, values are evaluated in a boolean context from left to right. 0, '', [], (), {}, and None are false in a boolean context; everything else is true. Well, almost everything. By default, instances of classes are true in a boolean context, but you can define special methods in your class to make an instance evaluate to false.

 

3Filtering Lists

[method for method in dir(object) if callable(getattr(object,method))]

关键词都加

关键要认准格式

 

4dir & getattr

 

dir returns a list of the attributes and methods of any object: modules, functions, strings, lists, dictionaries... pretty much anything.

 

getattr returns a reference to a function(method) of any object: modules, strings, lists, dictionaries… pretty much anything.

(我照着上面写的n_n,加粗的地方就是getattr的参数)

 

5Callable

the callable function takes any object and returns True if the object can be called, or False otherwise.

 

6lambda s

这是一个“简化”的function!格式是: lambda s: expression of s

它的返回值是expression of s 的结果。

可以把它assign给一个变量,如: g = lambda s: s.split()g是一个以s为参数的函数。

 

7str

str把非string类型的类型变成string类型,比如:

1 -> ‘ 1’

[ ] -> “[ ]”

None -> ‘None’

 

例子中之所以要用到str,是因为有些function doc string 可能没有,则返回None。
显示中用  %s ,则表明一定要为string类型的,用str做下装饰,遇到None也不怕了!

 


明白这些后,例子是不是也很容易理解了?

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值