python对象的正确和错误标准是什么?

编程入门 行业动态 更新时间:2024-10-20 09:27:45
本文介绍了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:

可以测试任何对象的真值,以用于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:

  • None

False

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

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__()方法,或者返回除True或False之外的其他值.前者是不寻常的,但有时是合理的行为(例如,请参见下面的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对象的正确和错误标准是什么?

本文发布于:2023-10-09 06:07:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1474907.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   正确   错误   标准   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!