为什么类型在Python中返回True?

2024-04-20 07:32:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我的理解正确吗if语句只有在计算True时才会“执行”?你知道吗

如果是这样,那么类型返回True的目的是什么?你知道吗

这条规则背后的逻辑是什么?你知道吗

有人能给我举个例子说明它在哪里有用吗?你知道吗

示例:

""" Example """

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

test(9)
test('\ntesting')

退货:

enter image description here


Tags: test目的true示例类型if规则example
3条回答

所有对象(包括类型,它们是type的实例)本质上都是真的,因为它们表示存在基础类型的值,而None表示不存在任何类型的值。(仅仅因为NoneNoneType的一个实例,所以None的计算结果为true是没有用的。)

某些类型的某些实例(空字符串和容器类型的空实例,仅举几例)的计算结果改为False,因为这样考虑比较方便。你知道吗

在您自己的类中,您可以重写特定实例的真值,方法是重写^{}__len__,为特定实例返回0或False。你知道吗

来自文档:

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.)

因为所有类型都是从object派生的,__nonzero__不返回False或integer zero,并且它们没有__len__方法,所以它被认为是True。你知道吗

还有一件有趣的事: ^float的{}是<slot wrapper '__nonzero__' of 'float' objects>

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

基本问题是:

What is the logic behind this rule?

这个规则是用来定义Python(should)如何操作的:只要有一个if语句的值不是TrueFalse,结果就应该很清楚。所有实现都一样!你知道吗

这并不意味着它是一种好的风格。也不应该用它

if float(3.14):
    print("is not a proper way to program")
 else:
    print("even it is clearly defined what will happen")

我个人不知道会印什么。我不会查的,反正是不好的。我总是告诉我的学生:“即使编译器理解了,你们学校也不会”

相关问题 更多 >