# 1. 引子

def enabled() -> bool:
a = ["a,"b"]
b = True
c = False
return (b and c) or (b and a)


# 2. python bool 类型简述

“The Boolean type is a subtype of the integer type, and Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings ‘False’ or ‘True’ are returned, respectively.”

“布尔类型是整数类型的一个子类型，在几乎所有的上下文环境中布尔值的行为类似于值0和1，例外的是当转换为字符串时，会分别将字符串”False“或”True“返回。“

>>> True == 1 == 1.0
True
>>> (hash(True), hash(1), hash(1.0))
(1, 1, 1)

>>> issubclass(bool, int)
True
>>> isinstance(True, int)
True
>>> isinstance(False, int)
True
>>> int(True)
1
>>> int(False)
0

>>> help(bool)

Help on class bool in module builtins:

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.


# 3. bool类型之间的 and 运算

and 运算符有两个操作数，可以是 bool，object，或一个组合

>>> True and True
True

>>> False and False
False

>>> True and False
False

>>> False and True
False


operand1 operand2 operand1 and operand2
True True True
True False False
False False False
False True False

expression1 and expression2

>>> 5>3 and 5==3+2
True


# 4. 不同类型之间的 and 运算

>>> 2 and 3
3
>>> 5 and 0.0
0.0
>>> [] and 3
[]
>>> 0 and {}
0
>>> 1 and {}
{}
>>> False and ""
False
>>> True and ""
''
>>> ["a"] and [1]
[1]


Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below.

By default, an object is considered true unless its class defines either a bool() method that returns False or a len() method that returns zero, when called with the object. 1 Here are most of the built-in objects considered false:

• constants defined to be false: None and False
• zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
• empty sequences and collections: '', (), [], {}, set(), range(0)

https://docs.python.org/3/library/stdtypes.html#truth-value-testing

object1 object2 object1 and object2
False False object1
False True object1
True True object2
True False object2

⚠️：如果在做对象逻辑运算，最终结果想得到 bool 类型 True/False的话，可以使用内建函数 bool(expression) 将结果重新实例化一下在返回

# 5. 高效运算-“快速短路”（short-circuit operator）

>>> def true_func():
...     print("Running true_func()")
...     return True
...

>>> def false_func():
...     print("Running false_func()")
...     return False
...

>>> true_func() and false_func()  # Case 1
Running true_func()
Running false_func()
False

>>> false_func() and true_func()  # Case 2
Running false_func()
False

>>> false_func() and false_func()  # Case 3
Running false_func()
False

>>> true_func() and true_func()  # Case 4
Running true_func()
Running true_func()
True


1. 将耗时的表达式放在 and 关键字的右侧。这样，如果短路规则生效，则不会运行代价高昂的表达式。
2. 将更有可能为 false 的表达式放在 and 关键字的左侧。这样， 更有可能通过仅计算左操作数来确定整个表达式是否为 false。

>>> def true_func():
...     print("Running true_func()")
...     return True
...

>>> def false_func():
...     print("Running false_func()")
...     return False
...

>>> # Use logical and
>>> false_func() and true_func()
Running false_func()
False

>>> # Use bitwise and
>>> false_func() & true_func()
Running false_func()
Running true_func()
False


# 6. bool 逻辑运算的万能公式

Operation Result Notes

Notes：

1. This is a short-circuit operator, so it only evaluates the second argument if the first one is false.
2. This is a short-circuit operator, so it only evaluates the second argument if the first one is true.
3. not has a lower priority than non-Boolean operators, so not a == b is interpreted as not (a == b), and a == not b is a syntax error.

def enabled() -> bool:
a = ["a,"b"]
b = True
c = False
return (b and c) or (b and a)


1. b and c --> 运用法则 2 (if x is false, then x, else y) 所以结果是 c 即 False
2. b and a --> a 运用法则 2 (if x is false, then x, else y) 所以结果是 a 即 ["a", "b"]
3. False or ["a", "b"] 运用法则 1 (if x is true, then x, else y) 所以结果是 ["a", "b"]

# 7. 参考

posted @ 2023-09-08 12:48  JonPan  阅读(114)  评论(0编辑  收藏  举报