Edit boolean and operator

So, I fiddled with the standard operators in the classes to try and see what I can do, but I could not find how to edit the logical operator and.

I can edit the bitwise operator &, defining __and__(self), but not in the way it behaves and. Does anyone know how I can change the behavior a and b, where aand bare instances of the class, which I do?

Thanks in advance!

+4
source share
2 answers

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> # evaluation stops at Test() because the object is falsy
>>> 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
+5

and boolean __bool__, (if first.__bool__() is True, return second, else return first). .

+4

Source: https://habr.com/ru/post/1691234/


All Articles