【2017/6】《流畅的Python》 (fluent python) 笔记

第一章 序幕

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__()方法

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值