“if”是否可以隐式访问 class 的特殊方法,即使它们没有被直接调用?

Does “if” have implicit access to a class’s special methods even when they are not directly called?

我不明白 for 循环中的代码如何知道 class 的实例是否为真。我的理解可能有误,但我认为正在发生的事情是这样的:对 bool 的调用调用了更改后的特殊方法 bool ,该方法已被修改为使用实例中内置的 len。但是在 class 之外,当我们到达 for 循环和 if 条件时,我不知道“if”如何知道订单是否真实,除非它调用特殊方法 bool(幕后)

如果这不是此类问题的论坛,我深表歉意,但我对所需术语的了解不够,无法在 google 上找到此问题的答案,也无法找到一本了解 OOP 的好书有 python 偏见。

代码

class Order:
    def __init__(self, cart, customer):
        self.cart = list(cart)
        self.customer = customer

   # def __bool__(self):
          #print("\'__bool__ got called\'")
          #return len(self.cart) > 0
        
order1 = Order(['banana', 'apple', 'mango'], 'Real Python')
order2 = Order([], 'Python')


for order in [order1, order2]:
    if order:
        print(f"{order.customer}'s order is processing...")
    else:
        print(f"Empty order for customer {order.customer}")


print(bool(order2))

请参考Python3 docs

简而言之,您的对象的基 class 有一个 __bool__ 函数,可以用来定义真实性。 如果它没有在类型上定义,那么将调用基础 class 实现。 它的功能如您所说,通过调用 __len__.

如果 __bool____len__ 都没有定义,则所有 class 对象都被认为是真实的。

根据@chepner 的评论对我的回答进行编辑:

为了计算 bool(Order()),Python 尝试:

  1. 找到 Order.__bool__,
  2. 的定义
  3. 然后是 __bool__ 的某个父 class 的定义。
  4. 如果还没有找到,它会寻找 Order.__len__
  5. 然后对于定义 __len__.
  6. 的父项
  7. 如果找到 none 个,那么 bool(Order()) 只需 returns True.