Python布尔逻辑混乱

2024-04-24 18:54:42 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能解释一下这些赋值语句背后的逻辑吗。你知道吗

>>> True
True
>>> True = False
>>> True
False
>>> True = True
>>> True
False
>>> a = True
>>> if a:
...     print "a is True"
... else:
...     print "a is False"
...
a is False

根据手册,bool类仅有的两个实例是TrueFalse。你知道吗

Help on bool object:

True = class bool(int)
 |  bool(x) -> bool
 |
 |  Returns True when the argument x is true, False otherwise.
 |  The builtins True and False are the only two instances of the class bool.
 |  The class bool is a subclass of the class int, and cannot be subclassed.
 |
 |  Method resolution order:
 |      bool
 |      int
 |      object

那么我要重写默认实例吗?如果是这样,为什么python在下面的赋值中不将True赋值给is default实例?如何在下面的语句中指定默认的pythonTrue?你知道吗

>>> True = False
>>> True
False
>>> True = True
>>> True
False     #why?

提前感谢您的帮助!!!你知道吗


Tags: andofthe实例falsetrueobjectis
1条回答
网友
1楼 · 发布于 2024-04-24 18:54:42

当您这样做时:

True = False

True变成False。。当你这么做的时候:

True = True

就像在写:

True = False

如果您想让它再次成为“原始”True,您应该:

>>> True = not True # recall that you assigned False to True
>>> True
True

相关问题 更多 >