当你有一个名为 max 的变量时使用 Python 的 max 函数?

Using Python's max function when you have a variable named max?

Python 包含内置的 max() 函数。然而,尽管它是内置的,但它不是关键字。也就是说,你可以做max=4。这是有道理的,因为某事的最大值出现了很多。但!如果您将 max 用作变量,则它会在该范围内禁用 max 函数。

所以如果你这样做:

max = 4
max(1, 2)

您将收到 int object not callable 的错误。再次,有道理。但是有什么方法可以指定您想要 max 函数吗?像 std.max()?这也适用于所有其他内置函数。

__builtin__ (Python 2) / builtins (Python 3) 模块提供了另一种访问所有 built-in/standard 标识符的方法,例如:

>>> import __builtin__
>>>
>>> __builtin__.max is max
True
>>>
>>> max = 2
>>> __builtin__.max([0, max])
2
import __builtin__ as builtins

def random_integer(min, max):
    random_integer.seed = builtins.max(10101, ( # looks random enough, right?
        ((random_integer.seed * 3 - 210) % 9898989) >> 1) ^ 173510713571)
    return min + (random_integer.seed % (max - min + 1))

random_integer.seed = 123456789

This module is not normally accessed explicitly by most applications, but can be useful in modules that provide objects with the same name as a built-in value, but in which the built-in of that name is also needed.

Python 3 中的名称更改是 the "core languages" changes described in PEP 3100 的一部分:

In order to get rid of the confusion between __builtin__ and __builtins__, it was decided to rename __builtin__ (the module) to builtins, and to leave __builtins__ (the sandbox hook) alone.