python对象的正确和错误标准是什么? [英] What are the true and false criteria for a python object?

查看:85
本文介绍了python对象的正确和错误标准是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到以下情况:

>>> def func(a):
...     if a:
...         print("True")
...
>>> a = [1, 2, 3]
>>> func(a)
True
>>> a == True
False

为什么会出现这种差异?

Why does this difference occur?

推荐答案

Python中的所有对象 1 都具有

All objects1 in Python have a truth value:

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

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:

  • None

False

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

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

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

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

任何空映射,例如{}.

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

instances of user-defined classes, if the class defines a __bool__() 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.


1 …,除非它们具有引发异常的__bool__()方法,或者返回除TrueFalse之外的其他值.前者是不寻常的,但有时是合理的行为(例如,请参见下面的user2357112的注释);后者不是.


1 … unless they have a __bool__() method which raises an exception, or returns a value other than True or False. The former is unusual, but sometimes reasonable behaviour (for example, see the comment by user2357112 below); the latter is not.

这篇关于python对象的正确和错误标准是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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