问题描述
在Python 2中,我们可以重新分配True
和False
(但不能重新分配None
),但是三个(True
,False
和None
)都被视为内置变量.但是,在Py3k中,根据文档将这三个变量都更改为关键字.. >
根据我自己的推测,我只能猜测这是为了防止像,它源自旧的True, False = False, True
恶作剧.但是,在Python 2.7.5以及之前的版本中,重新分配了None
的None = 3
这样的语句会引发SyntaxError: cannot assign to None
.
从语义上讲,我不相信True
,False
和None
是关键字,因为它们最终在语义上是文字,这是Java所做的.我检查了PEP 0(索引),却找不到说明为什么更改它们的PEP.
将关键字设置为文字或像python2中的None
那样特殊设置是否有性能优势或其他原因?
可能是因为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 所述, Python Wiki 在核心语言更改下也声明了以下内容:
- 输入True和False关键字.
- 原因:无法分配给他们.
In Python 2, we could reassign True
and False
(but not None
), but all three (True
, False
, and None
) were considered builtin variables. However, in Py3k all three were changed into keywords as per 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更改为关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!