python的作用域规则:LEGB原则








为什么Python会认为两个完全不同的对象拥有相等的值?在Python中布尔数据类型实际上是整数类型的子类。

在python3中,False和True是真正的保留字,而不是被定义在内置模块的名字空间(builtins)的名字。
在python2中他们只是内置模块中的名字。所以会得到值2.这是因为当我们使用+=给True赋值的时候,我们并没有改变True内置模块中的值。相反我们创造一个新的全局变量。内置模块中的值也存在,只是因为全局模块的名字有优先顺序,得到的值(2)覆盖了在内置模块的名字空间中的值(True或1)
网友评论