Python 2/3 差异点
内容 | python2 | python3 |
---|---|---|
关键字 | 函数 | |
编码 | 默认ASCII | 默认utf-8(unicode) |
除法 | 结果是int整除 | 结果是浮点数,整除是 // |
字符串问题
- 字节串是给机器看的
- unicode是给人看的
- python2中字符串两个类型:unicode-文本字符串和str-字节序列
- python3中 str-字符串,byte-字节序列
Python3 改进
- 类型注解(type hint),提示
>>> def hello(name:str) -> str:
... return "hello " + name
- 优化super()方法直接调用父类函数
super().hello()
- 高级解包操作。
a,b,*rest = range(10)
- 限定关键字参数
- Python3重新抛出异常不会丢失栈信息
- 一切返回迭代器 range,zip, map,dict.values.等
- 生成pyc文件放到__pycache__中
Python3 新增
- yield from 链接子生成器
- asyncio内置库,async/await 原生协程支持异步编程
- 新的内置库 enum,mock,asysncio,ipaddress等
Python2/3工具
- six 帮助编写兼容2/3的代码
- 2to3等工具转换代码