是否可以在 Python 中重载逻辑和?

Is it possible to overload logical and in Python?

我的印象是可以在 Python 中重载 and,但刚刚阅读文档,我意识到 __and__ 指的是按位 [=13] =] 运算符,不符合逻辑 and.

我是不是忽略了什么,或者是否无法在 Python 中重载逻辑 and

不,这是不可能的。参见 here

没有直接的方法可以做到这一点。您可以为您的对象覆盖 __nonzero__ 以修改它们的真值。

class Truth:

    def __init__(self, truth):
        self.truth = truth

    def __nonzero__(self):
        return self.truth

t = Truth(True)
f = Truth(False)

print bool(t and t)
print bool(t and f)
print bool(f and f)

不,这是不可能的。有一个 proposal 添加了此功能,但目前已被拒绝。