为什么在Python 3中将True和False更改为关键字 [英] Why were True and False changed to keywords in Python 3

查看:199
本文介绍了为什么在Python 3中将True和False更改为关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python 2中,我们可以重新分配TrueFalse(但不能重新分配None),但是三个(TrueFalseNone)都被视为内置变量.但是,在Py3k中,根据文档将这三个变量都更改为关键字.. >

根据我自己的推测,我只能猜测这是为了防止像解决方案

可能是因为Python 2.6不仅允许True = False,而且还允许您说一些有趣的事情,例如:

__builtin__.True = False

,整个过程会将True重置为False.它可以导致发生真正有趣的事情:

>>> import __builtin__
>>> __builtin__.True = False
>>> True
False
>>> False
False
>>> __builtin__.False = True
>>> True
False
>>> False
False

编辑:如 Mike 所述,the docs.

From my own speculation, I could only guess that it was to prevent shenanigans like this which derive from the old True, False = False, True prank. However, in Python 2.7.5, and perhaps before, statements such as None = 3 which reassigned None raised SyntaxError: cannot assign to None.

Semantically, I don't believe True, False, and None are keywords, since they are at last semantically literals, which is what Java has done. I checked PEP 0 (the index) and I couldn't find a PEP explaining why they were changed.

Are there performance benefits or other reasons for making them keywords as opposed to literals or special-casing them like None in python2?

解决方案

Possibly because Python 2.6 not only allowed True = False but also allowed you to say funny things like:

__builtin__.True = False

which would reset True to False for the entire process. It can lead to really funny things happening:

>>> import __builtin__
>>> __builtin__.True = False
>>> True
False
>>> False
False
>>> __builtin__.False = True
>>> True
False
>>> False
False

EDIT: As pointed out by Mike, the Python wiki also states the following under Core Language Changes:

  • Make True and False keywords.
    • Reason: make assignment to them impossible.

这篇关于为什么在Python 3中将True和False更改为关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆