为什么Python的bool内置函数只能查看类级别的__bool__方法 [英] Why does Python's bool builtin only look at the class-level __bool__ method
问题描述
文档明确指出
当未定义此方法(
__bool__
)时,将调用__len__()
(如果已定义),并且如果结果为非零,则将该对象视为true.如果 class 既未定义__len__()
也未定义__bool__()
,则其所有实例均被视为true.
When this method (
__bool__
) 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.
粗体字是我的插入词,斜体字是我的插入词,但实际上文本在这里.该类必须包含该方法的事实很容易通过
Bold is my insertion, italics is mine but the text is actually there. The fact that the class must contain the method is readily tested by
class A:
pass
a = A()
a.__bool__ = (lamda self: False).__get__(a, type(a))
print(bool(A()), bool(a))
如文档所述,结果为True True
.覆盖__len__
会得到相同的结果:
The result is True True
, as the documentation claims. Overriding __len__
yields the same result:
b = A()
b.__len__ = (lambda self: 0).__get__(b, type(b))
print(bool(A()), bool(b))
这完全按照文档要求的那样工作.但是,我发现这背后的原因有点违反直觉.我知道内置的bool
不会查看实例的方法,但是我不明白为什么.知道内部工作原理的人是否知道为什么只有类级别的__bool__
和__len__
方法会影响真实性,而实例级别的方法却被忽略了?
This works exactly as the documentation claims it will. However, I find the reasoning behind this to be a little counter-intuitive. I understand that the bool
builtin does not look at the methods of the instance, but I do not understand why. Does someone with a knowledge of the internal workings know why only the class-level __bool__
and __len__
methods affect truthiness while instance-level methods are ignored?