I tried overriding __and__, but that is for the & operator, not and – the one that I want. Can I override and?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
No you can’t override and and or. With the behavior that these have in Python (i.e. short-circuiting) they are more like control flow tools than operators and overriding them would be more like overriding if than + or -.
You can influence the truth value of your objects (i.e. whether they evaluate as true or false) by overriding __nonzero__ (or __bool__ in Python 3).
Method 2
You cannot override the and, or, and not boolean operators.
Method 3
Not really. There’s no special method name for the short-circuit logic operators.
Method 4
Although you can’t overload __and__ you can use infix to overload and. You would use &and& to represent the and operator in this case.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0