zoukankan      html  css  js  c++  java
  • from __future__ import包的作用

    __future__是python2的概念,其实是为了使用python2时能够去调用一些在python3中实现的特性

    1.absolute_import

    from __future__ import absolute_import

    这是一个在py2.x中导入3.x的导入特性的语句, 是为了区分出绝对导入和相对导入

    声明为绝对引用。因为在Python 2.4或之前默认是相对引用,即先在本目录下寻找模块。但是如果本目录中有模块名与系统(sys.path)模块同名冲突,而想要引用的是系统模块时,该声明就能够起作用了。这样你调用import string时引入的就是系统的标准string.py,调用from pkg import string来引入当前目录的string.py

    ⚠️但是其实最好是不要声明与系统模块同名的模块,如果实在需要同名,最好使用from XXX import XXX来导入

    2.division

    from __future__ import division

    在python3中默认是精确除法,而python2中默认的是截断式除法,如果在python2想要使用精确除法,就使用这个语句来声明

    在python2中如果没有声明,那么除法默认的是截断式除法,如:

    (deeplearning2) userdeMBP:~ user$ python
    Python 2.7.15 |Anaconda, Inc.| (default, Dec 14 2018, 13:10:39) 
    [GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> 3/4
    0
    >>> from __future__ import division
    >>> 3/4
    0.75

    当然,如果这个时候你想要使用截断式除法,为:

    >>> 3//4
    0

    3.print_function

    from __future__ import print_function

    即在python2中使用python3的print函数

    >>> print 'now in python2 it is right'
    now in python2 it is right
    >>> print('now in python2 it is right too')
    now in python2 it is right too
    
    >>> from __future__ import print_function
    >>> print 'now in python2 it is wrong'
      File "<stdin>", line 1
        print 'now in python2 it is wrong'
                                         ^
    SyntaxError: invalid syntax
    >>> print('now in python2 it is right')
    now in python2 it is right

    可见导入了后,使用python2的print则会报错

  • 相关阅读:
    DAY1 linux 50条命令
    安卓2.0,3.0,4.0的差别
    java历史
    晶体管共射极单管放大电路
    jquery取消选择select下拉框
    oarcle数据库导入导出,创建表空间
    360chrome,google chrome浏览器使用jquery.ajax加载本地html文件
    jquery 选择器
    nodejs 相关
    关于http请求
  • 原文地址:https://www.cnblogs.com/wanghui-garcia/p/10670738.html
Copyright © 2011-2022 走看看