负责对象 class 中的 `if obj:` 语句的特殊方法的名称是什么 python 中不包含 __boo__ 方法

What is the name of the special method responsible for `if obj:` statement in an object class which does not contain __boo__ method in python

我创建了一个包含 __bool__ 特殊方法的自定义对象,如下所示:

class CustomObject:
   def __init__(self, value):
       self.value = value
   def __bool__(self):
       print("This is from the __bool__ method")
       return True
obj = CustomObject(10)
if obj:
    print("Inside if")

输出:

This is from the __bool__ method
Inside if

if 语句调用 __bool__ 特殊方法。但是,在以下代码中,自定义模型不包含 __bool__ 特殊方法,但 if 语句的条件仍然为 True:

class CustomObject:
   def __init__(self, value):
       self.value = value

obj = CustomObject(10)
print(dir(obj))
if obj:
    print("Inside if")

输出:

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'value']
Inside if

所以我的问题是,if语句调用了上段的哪些特殊方法?

根据 Python 在 __bool__ 上的 documentation

Called to implement truth value testing and the built-in operation bool(); should return False or True. 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.

换句话说,如果 __bool__ 不存在,我们检查 __len__() != 0。如果 __len__ 不存在,答案总是 True.