In Python 2, andand oraccess __nonzero__:
>>> class Test(object):
... def __nonzero__(self):
... print '__nonzero__ called'
... return True
...
>>> Test() and 1
__nonzero__ called
1
In Python 3, it __nonzero__was renamed to __bool__.
>>> class Test:
... def __bool__(self):
... print('__bool__ called')
... return True
...
>>> Test() and 1
__bool__ called
1
, __nonzero__ __bool__.
>>> 0 and Test()
0
>>> 1 or Test()
1
, , , Python __len__, __nonzero__/__bool__ , __len__ , 0. , __nonzero__/__bool__.
>>> class Test:
... def __len__(self):
... return 23
...
>>> Test() and True
True
>>>
>>> class Test:
... def __len__(self):
... return 23
... def __bool__(self):
... return False
...
>>> Test() and True
<__main__.Test object at 0x7fc18b5e26d8>
>>> bool(Test())
False
, - , bool, , bools?
, . , False True, TypeError, - .
>>> class Test:
... def __bool__(self):
... return 1
...
>>> Test() and 42
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __bool__ should return bool, returned int
>>>
>>> bool(Test())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __bool__ should return bool, returned int