为什么python允许覆盖内置常量? [英] Why python allows to overwrite builtin constants?
问题描述
尽管 True
, False
是内置常量,Python中允许以下内容。
Although True
, False
are builtin constants, the following is allowed in Python.
>>> True = False
>>> a = True
>>> b = False
>>> print a,b
False False
为什么允许这样做?
编辑:这仅在Python 2.x中发生(如所指出的那样)。
This happens only in Python 2.x (as all pointed out).
推荐答案
请记住,这仅发生在python 3之前的Python版本中。这是Python理念的一部分,即一切都应该是动态的。
Keep in mind that this only happens in versions of Python that were before python 3. This was part of Python's philosophy that everything should be dynamic.
事实上,在Python 2中, True
不是关键字。它是对 bool
对象的引用绑定。您可以在python 2.x vm中尝试它:
In fact in Python 2 True
is not a keyword. It is a reference bound to a bool
object. You can try it in your python 2.x vm:
>>> type(True)
<type 'bool'>
在python 3中将其更改为关键字,并尝试在异常中重新绑定引用结果:
In python 3 it is changed to a keyword, and trying to rebind the reference results in an exception:
>>> True = []
File "<stdin>", line 1
SyntaxError: assignment to keyword
这篇关于为什么python允许覆盖内置常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!