Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to override the and operator in Python?

Tags:

python

I tried overriding __and__, but that is for the & operator, not and - the one that I want. Can I override and?

like image 859
airportyh Avatar asked Jan 23 '09 01:01

airportyh


People also ask

How do you override operators in Python?

In Python, overloading is achieved by overriding the method which is specifically for that operator, in the user-defined class. For example, __add__(self, x) is a method reserved for overloading + operator, and __eq__(self, x) is for overloading == .

Which operator Cannot be overloaded in Python?

Python does not limit operator overloading to arithmetic operators only. We can overload comparison operators as well. Suppose we wanted to implement the less than symbol < symbol in our Point class. Let us compare the magnitude of these points from the origin and return the result for this purpose.

How do you overload the comparison operator in Python?

Python has magic methods to define overloaded behaviour of operators. The comparison operators (<, <=, >, >=, == and !=) can be overloaded by providing definition to __lt__, __le__, __gt__, __ge__, __eq__ and __ne__ magic methods.

Which function overloads the >> operator Python?

Which function overloads the >> operator? Explanation: __rshift__() overloads the >> operator.


1 Answers

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

like image 123
dF. Avatar answered Sep 18 '22 15:09

dF.