我的理解是否正确,if
语句只有在计算结果为 True
时才会“执行”?
如果是这样,类型返回True
的目的是什么?
这条规则背后的逻辑是什么?
有人可以给我一个例子来说明它在哪里有用吗?
示例:
""" Example """
def test(x):
if float:
print("success")
test(9)
test('\ntesting')
返回:
最佳答案
来自文档:
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/