How to overload Python's __bool__ method? [dup

2019-03-11 14:06发布

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条回答
SAY GOODBYE
2楼-- · 2019-03-11 15:10

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.)

查看更多
登录 后发表回答