- 本页笔记专门用来做版本过渡的一些兼容改动
__future__模块
因为python更新的很勤快,而且经常出现版本不兼容问题。 __future__模块的出现就是为了让旧版本可以用到新版本的特性,从而进行项目版本的过渡。 被引用了__future__模块的.py文件其实就是变相的处于新版特性里面了。
- 字符串过渡
# 测试代码 print '\'xxx\' is unicode?', isinstance('xxx', unicode) print 'u\'xxx\' is unicode?', isinstance(u'xxx', unicode) print '\'xxx\' is str?', isinstance('xxx', str) print 'b\'xxx\' is str?', isinstance(b'xxx', str) ''' python2.7结果 'xxx' is unicode? False u'xxx' is unicode? True 'xxx' is str? True b'xxx' is str? True ''' ''' python3结果 'xxx' is unicode? True u'xxx' is unicode? True 'xxx' is str? False b'xxx' is str? True '''
- python2.x
'xxx' # 表示字符串 b'xxx' # 表示字符串 u'xxx' # 表示Unicode字符串
- python3.x
'xxx' # 表示Unicode字符串 u'xxx' # 表示Unicode字符串 b'xxx' # 表示字符串
- python2.x
除法过渡
新版本所有除法都默认是精确除法了
# 测试代码 from __future__ import division print '10 / 3 =', 10 / 3 print '10.0 / 3 =', 10.0 / 3 print '10 // 3 =', 10 // 3 ''' python2.7结果 10 / 3 = 3 10.0 / 3 = 3.33333333333 10 // 3 = 3 ''' ''' python3结果 10 / 3 = 3.33333333333 10.0 / 3 = 3.33333333333 10 // 3 = 3 '''
python2.x
整数相除(余数会直接丢弃)-> 地板除
10/3 = 3 # 地板除 10.0 / 3 = 3.33333333333 # 如果要精确必须转float进行运算
python3.x
所有的除法都是精确除法
10 / 3 = 3.33333333333 # 精确 10.0 / 3 = 3.33333333333 # 精确 10 // 3 = 3 # 两个/符号才代表地板除