下划线在python中意味着什么

时间:2013-11-28 20:33:31

标签: python python-2.7 python-3.x

大家好,因为从我的问题中可以明显看出我就像是蟒蛇的新手。 当我在python上阅读文档时,甚至在Stackoverflow论坛中,我都很困惑......

为什么他们这样写

from __future__ import division

围绕未来字的下划线是什么意思?我们是否应该像python解释器中的下划线一样使用它? 这只是众多例子中的一个。任何帮助都会非常有用。

2 个答案:

答案 0 :(得分:3)

根据提出此模块的PEP 236,双下划线使其成为保留名称。

[5] This ensures that a future_statement run under a release prior to
    the first one in which a given feature is known (but >= 2.1) will
    raise a compile-time error rather than silently do a wrong thing.
    If transported to a release prior to 2.1, a runtime error will be
    raised because of the failure to import __future__ (no such module
    existed in the standard distribution before the 2.1 release, and
    the double underscores make it a reserved name).

答案 1 :(得分:0)

以双下划线开头和结尾的名称(如__foo__)在Python中是special names(大多数是对象上的方法,__future__恰好是一个模块)。它们是特殊的,因为Python为它们附加了一些特殊的含义,它们被保留用于此目的。

你确实应该这样写。

这与只有__foo这样的前导双下划线的名称不同 - 这些名称受name mangling的约束,可用于创建类私有属性。

相关问题