How to overload Python's __bool__ method? [duplicate]

本秂侑毒 提交于 2019-12-03 05:25:41

问题


Possible Duplicate:
defining “boolness” of a class in python

I thought this should print "False", why is it printing "True"?

>>> class Foo(object):
...   def __bool__(self):
...     return False
... 
>>> f = Foo()
>>> if f:
...   print "True"
... else:
...   print "False"
... 
True
>>>

回答1:


You should define __nonzero__() in Python 2.x. It was only renamed to __bool__() in Python 3.x. (The name __nonzero__() actually predates the introduction of the bool type by many years.)



来源:https://stackoverflow.com/questions/8909932/how-to-overload-pythons-bool-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!