【2017/6】《流暢的Python》 (fluent python) 筆記

版權聲明:本文爲博主原創文章,未經博主允許不得轉載。 https://blog.csdn.net/hsgwpj/article/details/73835530

第一章 序幕

1.使用 with 操作文件來讓文件自動 close

Code:

with open('test.txt', 'w') as f:
    print type(f)
    f.write('helloworld!')
    print f

print type(f)
print f

Result:

<type 'file'>
<open file 'test.txt', mode 'w' at 0x0000000002ABF660>
<type 'file'>
<closed file 'test.txt', mode 'w' at 0x0000000002ABF660>

2.collections 類的使用 (nametuple 創建tuple對象)

import collections
Location = collections.namedtuple('Location', ['x', 'y'])
location = Location(1,2)

3.使用 random.choice來隨機抽取序列 choice(deck)
4.實現 __getitem__() 方法來支持 切片(slicing) 以及 迭代(iteration) : 你可以使用 for…in, in操作可迭代對象
5.對可迭代對象使用 sorted(args, key=some_method_name)同時定義key來確定排序規則
6.建議使用str.format() 來格式化輸出字符串 Tips: 使用 %r 而不是 %s 在__repr__()中輸出字符!
7.如果想把對象放入 if object: 中, 實現它的__bool__()方法

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章