类的nonzero方法用于将类转换为布尔值。通常在用类进行判断和将类转换成布尔值时调用。比如语句if A: print 'foo'中就会调用A.nonzero()来判断。下面这个程序应该能帮助你理解nonzero的作用。

class A:
  def __nonzero__(self):
    print 'A._nonzero__()'
    return True

print 'A is not zero' if A() else 'A is zero'
print bool(A())

output:

A._nonzero__()
A is not zero
A._nonzero__()
True


相关文章:

  • 2021-08-18
  • 2022-12-23
  • 2022-12-23
  • 2021-09-13
  • 2022-12-23
  • 2021-12-05
  • 2021-11-23
猜你喜欢
  • 2022-12-23
  • 2021-07-04
  • 2022-12-23
  • 2021-12-25
  • 2021-11-04
  • 2021-07-14
  • 2021-09-26
相关资源
相似解决方案