带有显式调用的字符串的truthy和falsy值

2024-06-28 19:20:45 发布

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

Python中的非空字符串应具有truthy值。为什么如果显式调用__bool__()函数,会出现错误?如果我使用if语句,它似乎会进行计算

>>> myvar = 'test'
>>> myvar.__bool__()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute '__bool__'
>>> if myvar:
...     print("myvar TRUTHY")
...
myvar TRUTHY
>>>

Tags: 函数字符串testmostif错误语句call
2条回答

字符串没有__bool__()方法(这是错误告诉您的)。相反,python将调用字符串上的__len__(),如果它不是零,则返回True。作为python data model mentions

When this method is not defined, __len__() is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither __len__() nor __bool__(), all its instances are considered true.

您可以通过创建UserString(或str)的子类并注意调用__len__()的时间来验证这一点。在布尔上下文中使用字符串时,将调用它:

from collections import UserString

class myString(UserString):
    def __len__(self):
        print("length called")
        return super().__len__()
    
s = myString("hello")

if s:
    pass
# prints "length called"

bool(s)
# length called
# True

根据Python documentation,真值检验依赖于__bool____len__方法。对于字符串,由于__bool__方法未定义,字符串的真值取决于已定义的__len__方法

相关问题 更多 >