为什么python允许覆盖内置常量? [英] Why python allows to overwrite builtin constants?

查看:108
本文介绍了为什么python允许覆盖内置常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管 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屋!

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