为什么Python内置类型名称不是保留关键字?

2024-04-24 08:31:53 发布

您现在位置:Python中文网/ 问答频道 /正文

换句话说,为什么Python允许变量名与内置类型名(如int、float、list等)相同?(C++的内置类型名称都是保留的,比较而言)。考虑一下这个例子

# int = 1
i = 2
if type(i) == int:
    print 'Is int'
else:
    print 'Not int'

输出是“is int”。但是,如果我取消注释第一行,输出将是“Not int”。显然我的“int”已经覆盖了内置的int类型,在我看来,这是潜在的危险。在


Tags: 名称类型ifistypenotfloatelse
2条回答

来自blog post on the History of Python by the Python language designer

Because you cannot use these as variable or function names anywhere, ever, in any Python program, everyone using Python has to know about all the reserved words in the language, even if they don't have any need for them. For this reason, we try to keep the list of reserved words small, and the core developers hem and haw a lot before adding a new reserved word to the language.

内置名称只是系统提供的对象,具有预定义值的变量。您可以根据模块或功能重新定义这些功能。使这个名称保留关键字(更大的列表)违背了上述理念。在

使内置类型和函数保留关键字也会使很难向该列表中引入任何新名称。添加到保留关键字列表会对前向兼容性产生严重影响。想象一下,在语言中添加一个color类型;为了避免使用这个新关键字,每一段用来处理图像的代码都需要重新编写。在

再次引用同一篇文章:

[W]hen we do decide to add a new keyword, we start a deprecation campaign at least one release before the new keyword is introduced, warning developers to choose a different name for their variables.

[...]

There's no such concern for built-ins. Code that happens to use the name of a new built-in as a variable or function name will continue to function (as long as you don't also try to use the new built-in in the same function). While we still try to be conservative with the introduction of new built-ins, at least we don't have to worry about breaking working code by merely adding something to the language.

These是所有保留的关键字。在

在解析python代码时,python解释器使用许多技术来确定用户想要做什么-可以包括行连接,例如如果代码包含这样的内容:

my_list = [1,
           2,
           3]

一般来说,Lexical Analysis:关键字帮助Python解释器理解程序员,通过他“按规则行事”。你不会(也不能)给一个变量命名for,因为当Python解释器读到这个词时,它知道其中涉及到一个循环,class(用于类声明)和所有关键字都是相同的(它们都在我们的程序中执行特定的角色)。在

为什么内置类型不是保留字?因为Python解释器不是这样工作的,所以理解您在某个时刻给变量赋值是没有问题的。在

更多信息(除了给出的链接)可以在here找到。在

相关问题 更多 >