关于 from __future__ import (***) 模块的使用

今天在学习目标检测的Python接口代码是,对于image检测的Python的第一行便出现了:from __future__ import print_function。经过查找,原来这是为了在老版本的Python中兼顾新特性的一种方法。具体地,如下:

从python2.1开始以后, 当一个新的语言特性首次出现在发行版中时候, 如果该新特性与以前旧版本python不兼容, 则该特性将会被默认禁用. 如果想启用这个新特性, 则必须使用 "from __future__import *" 语句进行导入.

示例:

1. Python 2.7中也有一个 __future__ import 使得所有的字符串文本成为Unicode字符串。这就意味着\u转义序列可以用于包含Unicode字符。

    from __future__ import unicode_literals  
    s = ('am I a unicode?')  
    print isinstance(s, unicode)

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方法
---------------------

文章来源:https://blog.csdn.net/wonengguwozai/article/details/75267858
 

猜你喜欢

转载自blog.csdn.net/ATOOHOO/article/details/88679993