Python的__future__模块

转自:https://www.cnblogs.com/linyihan/p/5644262.html

Python的每个新版本都会增加一些新的功能,或者对原来的功能作一些改动。有些改动是不兼容旧版本的,也就是在当前版本运行正常的代码,到下一个版本运行就可能不正常了。

从Python 2.7到Python 3.x就有不兼容的一些改动,比如2.x里的字符串用'xxx'表示str,Unicode字符串用u'xxx'表示unicode,而在3.x中,所有字符串都被视为unicode,因此,写u'xxx'和'xxx'是完全一致的,而在2.x中以'xxx'表示的str就必须写成b'xxx',以此表示“二进制字符串”。

要直接把代码升级到3.x是比较冒进的,因为有大量的改动需要测试。相反,可以在2.7版本中先在一部分代码中测试一些3.x的特性,如果没有问题,再移植到3.x不迟。

Python提供了__future__模块,把下一个新版本的特性导入到当前版本,于是我们就可以在当前版本中测试一些新版本的特性。举例说明如下:

为了适应Python 3.x的新的字符串的表示方法,在2.7版本的代码中,可以通过unicode_literals来使用Python 3.x的新的语法:

# still running on Python 2.7

from __future__ import unicode_literals

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)

注意到上面的代码仍然在Python 2.7下运行,但结果显示去掉前缀u的'a string'仍是一个unicode,而加上前缀b的b'a string'才变成了str:

$ python task.py
'xxx' is unicode? True
u'xxx' is unicode? True
'xxx' is str? False
b'xxx' is str? True

类似的情况还有除法运算。在Python 2.x中,对于除法有两种情况,如果是整数相除,结果仍是整数,余数会被扔掉。

========================================================================================

转自:https://blog.csdn.net/wonengguwozai/article/details/75267858

2. Python 2.7可以通过 import __future__ 来将2.7版本的print语句移除,让你可以Python3.x的print()功能函数的形式。例如:

from __future__ import print_function  
print('hello', end='\t') 
 

3. 整数除法

python 2.7中:>>>23/6  >>>3  
from __future__ import division 之后:  
>>>23/6   >>> 3.8333333333333335 
 

4. with特性

from __future__ import with_statement

with open('test.txt', 'r') as f:
    for line in f:
        print line

with方式语句可以替换以前try..catch语句, 如果使用try..catch语句则为:
try:
    f = open('test.txt', 'r')
    for line in f:
        print line
finally:
    f.close()
而with代码块如果内部出现任何错误, 都将会自动调用close方法
 

猜你喜欢

转载自blog.csdn.net/Song_Esther/article/details/83144554
今日推荐