在Python如何从笑话之类的语句真=假恢复

问题描述 投票:3回答:3

我开始就在今天使用Python 2.7学习Python和我在这里有一个问题,关于真与假的全局变量:

看来我可以覆盖真假,因为这值:

False = True
# now the value of variable False is also true.
True = False
# because the value of False is true, after this the value of True is still true.

if True(or False):
    print 'xxxx'
else:
    print 'yyyy'

现在羯羊我们把真正的或我们把假的,如果条件下,它总是打印“XXXX”。

那么如何从故障状态中恢复?我想,我们可以使用这样的:

True = 1==1
False = 1!=1

但似乎有些冒险。有没有更好的方式来做到这一点?

谢谢。

(此外,它似乎在Python 3.3这个动作不再允许?)

python python-2.7
3个回答
3
投票

从这个“恢复”的方法是不让它发生。

这就是说,你可以随时使用bool()式访问True并再次False。 (bool()总是返回两个布尔单身一个。)

例:

>>> bool
<type 'bool'>
>>> bool(1)
True
>>> bool(1) is bool('true')
True
>>> True = False
>>> True
False
>>> True is False
True
>>> False is bool()
True
>>> True = bool(1)
>>> True is bool(1)
True
>>> True is False
False
>>> True is bool()
False
>>> bool()
False
>>> True is bool(2)
True
>>> True is bool('true')
True
>>> 

如果这是一个简单的True = 'something'结合,然后发生的事情是一个新的名字True在当前命名空间中创建 - 在__builtins__模块没有改变。在这种情况下,你可以简单地删除(解除绑定)“真实”在您的命名空间名称。那么Python将使用__builtins__重新定义的。

>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
>>> True is __builtins__.True
True
>>> True = 'redefined'
>>> __builtins__.True is True
False
>>> del True
>>> __builtins__.True is True
True

这一切都不是可能在Python 3,因为TrueFalse不再名称(变量),但关键字。


4
投票

他们不是“全局”变量,因为这样 - 他们是内置插件....他们在__builtin__(无S)可用的 - 你可以做你会“的笑话”。需要注意的是做这种事情主要是为嘲笑那亲属/廓线和东西...

不,你不能这样做,在3.x系列,因为TrueFalse是关键字,而不是(那种)单身像2.X


3
投票

如果事情都差不太多,你可以设置True = __builtins__.True

© www.soinside.com 2019 - 2024. All rights reserved.