Why is bool(x) where x is any integer equal to True
我期望使用python时
1 2 3 | >>> x=23 #<-- replace with any integer >>> bool(x) True |
发生什么事了?我是否误解了
很多关于为什么我觉得这是反直觉的评论。如果我这样写上面的话,那么,第一眼看不到语言知识,这似乎是违反直觉的:
1 2 | >>>True == bool(23) True |
从5.1真值测试:
The following values are considered false:
None False - zero of any numeric type, for example,
0 ,0L ,0.0 ,0j .- any empty sequence, for example,
'' ,() ,[] .- any empty mapping, for example,
{} .- instances of user-defined classes, if the class defines a
__nonzero__() or__len__() method, when that method returns the integerzero orbool valueFalse .All other values are considered true — so objects of many types are
always true.
正如其他海报所提到的,它在任何非零整数上都是正确的。
它类似于Python中的其他东西,如这里提到的:
python"if not"语法
(罗希特引用了一段关于真理测试的好段落)
检查真值测试,查看在python中哪些值被视为
1 2 3 4 5 | def bool_mimic(val): if val: return True else: return False |
来自文档:
bool([x])
Convert a value to a Boolean, using the standard truth testing procedure [see Rohit's answer]. If x is false or omitted, this returns
False ; otherwise it returnsTrue .bool is also a class, which is a subclass ofint . Classbool cannot be subclassed further. Its only instances areFalse andTrue .< /块引用>
在int的情况下,唯一的非真整数是
0 。