【python】from __future__ import absolute_import/division/print_function

from __future__ import absolute_import

关于这句from __future__ import absolute_import的作用: 
直观地看就是说”加入绝对引入这个新特性”。说到绝对引入,当然就会想到相对引入。那么什么是相对引入呢?比如说,你的包结构是这样的: 
pkg/ 
pkg/init.py 
pkg/main.py 
pkg/string.py

如果你在main.py中写import string,那么在Python 2.4或之前, Python会先查找当前目录下有没有string.py, 若找到了,则引入该模块,然后你在main.py中可以直接用string了。如果你是真的想用同目录下的string.py那就好,但是如果你是想用系统自带的标准string.py呢?那其实没有什么好的简洁的方式可以忽略掉同目录的string.py而引入系统自带的标准string.py。这时候你就需要from __future__ import absolute_import了。这样,你就可以用import string来引入系统的标准string.py, 而用from pkg import string来引入当前目录下的string.py了

 from __future__ import division

导入python未来支持的语言特征division(精确除法),当我们没有在程序中导入该特征时,"/"操作符执行的是截断除法(Truncating Division),当我们导入精确除法之后,"/"执行的是精确除法。

---------------------------------------------------------------------------------------------
>>> 3/4
0
>>> from __future__ import division
>>> 3/4
0.75

--------------------------------------------------------------------------------------------

导入精确除法后,若要执行截断除法,可以使用"//"操作符:
--------------------------------------------------------------------------------------------
>>> 3//4
0
>>> 
--------------------------------------------------------------------------------------------
一些将来特征如下:
feature    optional in    mandatory in    effect
nested_scopes    2.1.0b1    2.2    PEP 227: Statically Nested Scopes
generators    2.2.0a1    2.3    PEP 255: Simple Generators
division    2.2.0a2    3.0    PEP 238: Changing the Division Operator
absolute_import    2.5.0a1    2.7    PEP 328: Imports: Multi-Line and Absolute/Relative
with_statement    2.5.0a1    2.6    PEP 343: The “with” Statement
print_function    2.6.0a2    3.0    PEP 3105: Make print a function
unicode_literals    2.6.0a2    3.0    PEP 3112: Bytes literals in Python 3000
PEP:Python Enhancement Proposals
可以在这个地方找到很多PEP:http://www.python.org/dev/peps/ 里面还能看到许多提议的动机
比如有division:
The current division (/) operator has an ambiguous meaning for numerical arguments: 
it returns the floor of the mathematical  result of division if the arguments are ints or longs, but it returns a reasonable approximation of the division result if the arguments are floats or complex.  
This makes expressions expecting float or complex results error-prone when integers are not expected but possible as inputs.

from __future__ import print_function

在开头加上这句之后,即使在python2.X,使用print就得像python3.X那样加括号使用。python2.X中print不需要括号,而在python3.X中则需要。

# python2.7 

print "Hello world" 

# python3 

print("Hello world")

 

  • 9
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值