gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:46:24 27 4
gpt4 key购买 nike

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

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

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

最佳答案

来自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.

关于python - 为什么 Python 内置类型名称不是保留关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30525262/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com