在 "while A:" 中对 A 调用了什么操作?
What operation is called on A in "while A:"?
假设我有:
class Bar:
pass
A = Bar()
while A:
print("Foo!")
然后在 A
上调用什么操作来确定 while
循环?
我试过 __eq__
但效果不大。
用户定义的对象是真实的,除非你定义一个自定义的__bool__
:
>>> class A:
... pass
...
>>> a = A()
>>> if a: print(1)
...
1
>>> class B:
... def __bool__(self):
... return False
...
>>> b = B()
>>> if b: print(1)
...
>>>
while
statement 由 while
关键字后跟一个表达式组成。
当 expression is used in a control flow statement 通过调用对象 __bool__
方法评估该表达式的真值时:
In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False
, None
, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. User-defined objects can customize their truth value by providing a __bool__()
method.
总之,结果取决于你的对象__bool__
是什么returns;由于您没有指定,因此使用默认值 True
。
可以调用不同的方法来确定对象的计算结果是 True
还是 False
。
如果定义了 __bool__
方法,则调用此方法,否则,如果定义了 __len__
,则将其结果与 0
.
进行比较
假设我有:
class Bar:
pass
A = Bar()
while A:
print("Foo!")
然后在 A
上调用什么操作来确定 while
循环?
我试过 __eq__
但效果不大。
用户定义的对象是真实的,除非你定义一个自定义的__bool__
:
>>> class A:
... pass
...
>>> a = A()
>>> if a: print(1)
...
1
>>> class B:
... def __bool__(self):
... return False
...
>>> b = B()
>>> if b: print(1)
...
>>>
while
statement 由 while
关键字后跟一个表达式组成。
当 expression is used in a control flow statement 通过调用对象 __bool__
方法评估该表达式的真值时:
In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false:
False
,None
, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. User-defined objects can customize their truth value by providing a__bool__()
method.
总之,结果取决于你的对象__bool__
是什么returns;由于您没有指定,因此使用默认值 True
。
可以调用不同的方法来确定对象的计算结果是 True
还是 False
。
如果定义了 __bool__
方法,则调用此方法,否则,如果定义了 __len__
,则将其结果与 0
.