Overriding logical operators?
Michael J. Fromberger
Michael.J.Fromberger at Clothing.Dartmouth.EDU
Sat Aug 21 21:38:01 EDT 2004
In article <mailman.2095.1093066795.5135.python-list at python.org>,
Andrew Durdin <adurdin at gmail.com> wrote:
> In Python, you can override the behaviour of most operators for a
> class, by defining __add__, __gt__, and the other special object
> methods.
>
> I noticed that, although there are special methods for most operators,
> they are conspicuously absent for the logical "or" and "and". I'm
> guessing that the reason for this is that these operators
> short-circuit if their first operand answers the whole question?
>
> Would it be possible to allow overriding the logical operators, with
> the caveat that overriding it would prevent short-circuiting?
The implementation of "and" and "or" are special, as others have pointed
out. However, you do have some control over how they behave for objects
of user-defined classes. By overriding __nonzero_, you can define
whatever truth value you like for instances of a user-defined class.
See:
http://docs.python.org/lib/truth.html
This would not, in itself, "override" the behaviour of "and" and "or",
in the sense that you were describing, but it would let you control the
outcome for objects of your particular class.
-M
--
Michael J. Fromberger | Lecturer, Dept. of Computer Science
http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA
More information about the Python-list
mailing list