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了

参考:https://docs.python.org/2.5/whatsnew/pep-328.html
http://stackoverflow.com/questions/7075082/what-is-future-in-python-used-for-and-how-when-to-use-it-and-how-it-works

  • 56
    点赞
  • 115
    收藏
    觉得还不错? 一键收藏
  • 16
    评论
引用\[1\]: 如果你想使用import string来引入系统自带的string.py,而不是当前目录下的string.py,你可以使用from __future__ import absolute_import这句话。这样,你就可以使用import string来引入系统自带的string.py,同时使用from pkg import string来引入当前目录下的string.py。\[1\] 引用\[2\]: 这句from __future__ import absolute_import作用是引入"绝对引入"。在python2.4或之前的版本中,如果你在代码中写入import string,python会先查找当前目录下是否有string.py,如果有,则引入该模块。但如果你想使用系统自带的标准string.py,而不是当前目录下的string.py,就需要使用from __future__ import absolute_import这句话。这样,你就可以使用import string来引入系统自带的标准string.py,同时使用from pkg import string来引入当前目录下的string.py。\[2\] 所以,当你在python2.4之后的环境下运行代码时,不需要加上from __future__ import absolute_import这句话。但如果你在python2.4或之前的环境下运行代码,并且想要引入系统自带的标准string.py,就需要加上这句话。\[1\]\[2\] #### 引用[.reference_title] - *1* *2* [【Python】from __future__ import absolute_import作用](https://blog.csdn.net/qq_15971883/article/details/121527294)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [from __future__ import absolute_import作用](https://blog.csdn.net/u012206617/article/details/106493749)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值