在python真相测试中,bool()与==之间有什么区别吗? [英] Is there any difference between bool() vs == in python truth testing?

查看:110
本文介绍了在python真相测试中,bool()与==之间有什么区别吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个问题.

  1. 由bool()方法调用时,python中的任何内容(对象,类型,操作,函数..)都可以返回布尔值吗?

  1. Can ANYTHING (objects, types, operations, functions..) in python return a boolean value when it is called upon by the bool() method?

下面的两行代码为什么不返回相同的答案?

Why dont the following two lines of code return the same answer?

print (float == True)  #prints False
print bool(float)      #prints True

推荐答案

==bool()这两个是不同的. ==用于相等性测试,而bool()返回作为参数传递给它的对象的真值测试结果.

The two, == and bool(), are different. == is for equality testing, whereas bool() returns the result of truth value testing for the object passed to it as parameter.

根据bool()-

类bool([x])

返回一个布尔值,即True或False之一. x是使用标准真值测试过程转换的.如果x为false或省略,则返回False;否则为false.否则返回True.

Return a Boolean value, i.e. one of True or False. x is converted using the standard truth testing procedure. If x is false or omitted, this returns False; otherwise it returns True.

标准真相测试过程可以在文档中找到-

The standard truth testing procedure can be found in the documentation -

可以测试任何对象的真值,以便在if或while条件中使用或用作以下布尔运算的操作数.以下值被认为是错误的:

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:

  1. None

False

任何数字类型的零,例如00L0.00j.

zero of any numeric type, for example, 0, 0L, 0.0, 0j.

任何空序列,例如''()[].

any empty sequence, for example, '', (), [].

任何空映射,例如{}.

实例,如果该类定义了__nonzero__()__len__()方法,则当该方法返回整数零或布尔值False时.

instances of user-defined classes, if the class defines a __nonzero__() or __len__() method, when that method returns the integer zero or bool value False.

所有其他值都视为True-因此许多类型的对象始终为true.

All other values are considered True — so objects of many types are always true.

当您执行bool(float)时,您正在检查float的真值,即True.

When you do bool(float), you are checking the truth value for float, which is True.

但是,当您执行float == True时,您正在做相等操作(请注意,这不是真值测试,而是相等).在这种情况下,floatTrue不相等,从而导致False.

But when you do float == True, you are doing equality (please note this is not truth value testing, it is equality). In this case float and True are not equal so that results in False.

这篇关于在python真相测试中,bool()与==之间有什么区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆