加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 12:32:18 所属栏目:Python 来源:网络整理
导读:换句话说,为什么 Python允许与内置类型名称相同的变量名,如int,float,list等? (相比之下,C内置类型名称都是保留的).考虑这个例子 # int = 1i = 2if type(i) == int: print 'Is int'else: print 'Not int' 输出为“Is int”.但是,如果我取消注释第一行,则输
换句话说,为什么 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.也就是说,在我看来,有潜在危险.

解决方法

从 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.

内置名称只是系统提供的对象,具有预定义值的变量.您可以逐个模块或逐个函数地重新定义它们.使这个(相当大的列表)名称保留关键字将违背上述原则.

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

再次引用同一篇文章:

[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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读