假设我有一个列表Q
。在下面的代码中:
while Q:
do_something()
Q.pop()
在while Q
语句中,调用了列表Q
的什么方法?是__len__
方法吗?
最佳答案
在 Python 3.x 中,它是 __bool__
或__len__
:
object.__bool__(self)
Called to implement truth value testing and the built-in operation
bool()
; should returnFalse
orTrue
. 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.
在 2.x 中它被命名为 __nonzero__
;请参阅what's new in 3.0 .
关于python - 验证集合时调用的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43708561/