看个栗子先
mixed_list = [False, 1, 3, True, 5]
integer_sum = 0
bool_sum = 0
for item in mixed_list:
if isinstance(item, int):
integer_sum += 1
elif isinstance(item, bool):
bool_sum += 1
print(integer_sum) # 5
print(bool_sum) # 0
为什么 bool_sum
= 0, 而不是bool_sum
= 2?
- 看源码可知,
bool
是int
的子类 - 所以
True
的整数值是 1, 而False
的整数值是 0
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.
"""