Python 中的 __future__ 是什么,如何/何时使用,以及它是如何工作的 [英] What is __future__ in Python used for and how/when to use it, and how it works

查看:47
本文介绍了Python 中的 __future__ 是什么,如何/何时使用,以及它是如何工作的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

__future__ 经常出现在 Python 模块中.即使在阅读了 __future__ 的用途以及如何/何时使用它">Python 的 __future__ 文档.

谁能用例子解释一下?

我收到的一些关于 __future__ 基本用法的答案似乎是正确的.

但是,关于 __future__ 的工作原理,我还需要了解一件事:

对我来说最令人困惑的概念是当前的 Python 版本如何包含未来版本的功能,以及如何在当前版本的 Python 中成功编译使用未来版本功能的程序.

我猜测当前版本包含了未来的潜在功能.但是,这些功能只能通过使用 __future__ 来使用,因为它们不是当前的标准.让我知道我是否正确.

解决方案

通过包含 __future__ 模块,您可以慢慢习惯不兼容的更改或引入新关键字的更改.

例如,要使用上下文管理器,您必须在 2.5 中执行 from __future__ import with_statement,因为 with 关键字是新的,不应用作变量名不再.为了在 Python 2.5 或更早版本中使用 with 作为 Python 关键字,您需要使用上面的导入.

另一个例子是

from __future__ 导入师打印 8/7 # 打印 1.1428571428571428打印 8//7 # 打印 1

如果没有 __future__ 的东西,两个 print 语句都会打印 1.

内部区别在于,如果没有那个导入,/ 被映射到 __div__() 方法,而有了它,__truediv__()用来.(无论如何,// 调用 __floordiv__().)

Apropos print:print 在 3.x 中变成了一个函数,失去了它作为关键字的特殊属性.所以情况正好相反.

<预><代码>>>>打印>>>从 __future__ 导入 print_function>>>打印<内置函数打印>>>>

__future__ frequently appears in Python modules. I do not understand what __future__ is for and how/when to use it even after reading the Python's __future__ doc.

Can anyone explain with examples?

A few answers regarding the basic usage of __future__ I've received seemed correct.

However, I need to understand one more thing regarding how __future__ works:

The most confusing concept for me is how a current python release includes features for future releases, and how a program using a feature from a future release can be be compiled successfully in the current version of Python.

I am guessing that the current release is packaged with potential features for the future. However, the features are available only by using __future__ because they are not the current standard. Let me know if I am right.

解决方案

With __future__ module's inclusion, you can slowly be accustomed to incompatible changes or to such ones introducing new keywords.

E.g., for using context managers, you had to do from __future__ import with_statement in 2.5, as the with keyword was new and shouldn't be used as variable names any longer. In order to use with as a Python keyword in Python 2.5 or older, you will need to use the import from above.

Another example is

from __future__ import division
print 8/7  # prints 1.1428571428571428
print 8//7 # prints 1

Without the __future__ stuff, both print statements would print 1.

The internal difference is that without that import, / is mapped to the __div__() method, while with it, __truediv__() is used. (In any case, // calls __floordiv__().)

Apropos print: print becomes a function in 3.x, losing its special property as a keyword. So it is the other way round.

>>> print

>>> from __future__ import print_function
>>> print
<built-in function print>
>>>

这篇关于Python 中的 __future__ 是什么,如何/何时使用,以及它是如何工作的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆