python - 为什么 Python 中的类型返回 True?

标签 python python-3.x if-statement types

我的理解是否正确,if 语句只有在计算结果为 True 时才会“执行”?

如果是这样,类型返回True的目的是什么?

这条规则背后的逻辑是什么?

有人可以给我一个例子来说明它在哪里有用吗?

示例:

""" Example """

def test(x):
    if float:
        print("success")

test(9)
test('\ntesting')

返回:

enter image description here

最佳答案

来自文档:

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

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 integer zero or bool value False. [1]

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

Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated. (Important exception: the Boolean operations or and and always return one of their operands.)

由于所有类型都是从对象派生的,__nonzero__不返回 False 或整数零,并且它们没有 __len__方法,则视为 True。

还有一件有趣的事情: __nonzero__ float 为<slot wrapper '__nonzero__' of 'float' objects>

以下是一些相关信息: What is a wrapper_descriptor, and why is Foo.__init__() one in this case?

关于python - 为什么 Python 中的类型返回 True?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32383040/

相关文章:

python - 使用 Python 抓取 .aspx 表单

python - 属性错误: partially initialized module 'face_recognition' has no attribute 'face_encodings'

python - 使用 Popen 减少控制

javascript - 在 if 语句中使用字符串的内容作为条件

c++ - 比较运算符 == 不起作用,我该如何让它起作用? [cpp]

java - Android Studio if 语句与 OR (||) 函数

python - 在 pytorch 中计算 `loss.backward` 的多重损失性能吗?

python - 为什么这些元组值似乎失去了精度

python - 从 numpy 数组中查找并删除列

python - 从类定义中的列表理解访问类变量