python:from __future__ import 的含义

__future__模块是为了在当前版本python中使用新python3.x特性而加入的语法。

这个模块里包含了(对于当前版本而言)没有加入当前版本python的新特性。

使用方法如下,在文件开头书写下面语句,否则会起SyntaxError

from __future__ import *

python的新特性会在某一个版本之后被强制地加入发行版本,但是没被强制加入发行版本的特性是新旧兼容的。这个会在下文中提到。一些经典的特性见下表:

在这里插入图片描述

想查看有哪些新特性,可以使用下面的代码:

# python 3.8.12
>>> import __future__
>>> print(__future__.all_feature_names)
['nested_scopes', 'generators', 'division', 'absolute_import', 'with_statement', 'print_function', 'unicode_literals', 'barry_as_FLUFL', 'generator_stop', 'annotations']

下面是几个例子:

1. print_function

在python2中,print函数长这样:

# python2
print "hello world"

但是在python3中,print函数长这样:

# python3
print("hello world")

在python2中,两种写法都是可以直接用的:

# python2
>>> print "hello world"
hello world
>>> print("hello world")
hello world

但是一旦使用了from __future__ import print_function语句,python2的语法就不再生效:

扫描二维码关注公众号,回复: 13715970 查看本文章
from __future__ import print_function

>>> print("hello world")
hello world
>>> print "hello world"
  File "/home/0a506b14e8975b8a788846c5356abb76.py", line 4
    print "Hello world"
                      ^
SyntaxError: invalid syntax

2. division

python2中的除法/是地板除,即除数向下取整。但是python3里的除法是精确除法:

# python2
>>> print 7 / 5
1
>>> print -7 / 5
-2
# In below python 2.x code, division works
# same as Python 3.x because we use  __future__
   
>>> from __future__ import division     
>>> print 7 / 5
1.4
>>> print -7 / 5
-1.4

猜你喜欢

转载自blog.csdn.net/weixin_43466027/article/details/121396209
今日推荐