473,756 Members | 5,156 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Overriding logical operators?

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?
Jul 18 '05 #1
3 3793
In article <ma************ *************** ***********@pyt hon.org>,
Andrew Durdin <ad*****@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
Jul 18 '05 #2
On Sat, 21 Aug 2004 21:38:01 -0400, Michael J. Fromberger
<mi************ ******@clothing .dartmouth.edu> wrote:

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.


I suppose now I ought to say why I need to to do more than that. I've
got a situation where I want to construct an expression, but evaluate
it later when I get more information. I came up with a "DelayedEva l"
class, the instances of which can have operations performed on them,
but the result is not evaluated until a particular method is called.
I'm currently overriding all the operators I can, so that these
instances can be handled in a fairly normal fashion for the most part.
For example:

foo = DelayedEval()
foo = (-foo + 15) * 3
foo_positive = (foo >= 0)

print foo.evaluate(10 ) # prints 15
print foo.evaluate(20 ) # prints -15
print foo_positive.ev aluate(10) # prints True
print foo_positive.ev aluate(20) # prints False

In this situation, merely overriding the __nonzero__ method will not
allow me to delay the evaluation of the logical boolean operators; to
do that I need to be able to override them.

The alternative solution that I can see to the issue is to use lambdas
to create the expressions I need, and calling them to evaluate them,
e.g.:

foo = lambda v: (-v + 15) * 3
foo_positive = lambda v: (foo(v) >= 0)

This will work, but having to manually chain the evaluation in this
way is a little awkward. It also doesn't allow me to print the
expressions. With the DelayedEval class, I can do this:

print foo_positive # prints (((-(value) + 15) * 3) >= 0)
Jul 18 '05 #3
Andrew Durdin <ad*****@gmail. com> writes:
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".
That's because they're not operators, they're flow control constructs.
Well, maybe that's not a helpful answer, but it's one you haven't had
yet :-)
Would it be possible to allow overriding the logical operators, with
the caveat that overriding it would prevent short-circuiting?


I think this would be a foul abomination. But maybe that's just me.
(I don't really approve of operator overloading either).

Cheers,
mwh

--
Ability to type on a computer terminal is no guarantee of sanity,
intelligence, or common sense.
-- Gene Spafford's Axiom #2 of Usenet
Jul 18 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1533
by: Andrew Durdin | last post by:
On Fri, 20 Aug 2004 23:28:20 -0700, Robert Brewer <fumanchu@amor.org> wrote: > > The first barrier is that 'or' and 'and' get compiled down to jump > codes, as opposed to operations: > ....so you'd be hacking a completely different section of the compiler to > enable such overriding.
3
7802
by: Cheng Mo | last post by:
When overriding operator new & delte of one class, the method is implicitly declared as static. However, overriding operator new & delete of template cannot be static.The compiler says cannot declare the function a static linkage. Why? C++ is so complex and so many situation should be considered.
80
35130
by: Christopher Benson-Manica | last post by:
Of course one can get the effect with appropriate use of existing operators, but a ^^ operator would make for nice symmetry (as well as useful to me in something I'm working on). Am I the only one who would find it useful? -- Christopher Benson-Manica | I *should* know what I'm talking about - if I ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
18
4743
by: JohnR | last post by:
From reading the documentation, this should be a relatively easy thing. I have an arraylist of custom class instances which I want to search with an"indexof" where I'm passing an instance if the class where only the "searched" property has a value. I expected to get the index into the arraylist where I could then get the entire class instance. However, the 'indexof' is never calling my overloaded, overrides Equals method. Here is the...
2
4120
by: ThunderMusic | last post by:
Hi, I have a value that contains flags that I must get using a bitmask. I tryied with the && operator, but the compiler outputs this error : Operator '&&' cannot be applied to operands of type 'int' and 'int' The code is the following : // MASKS.Insert = 2 if (_RightMask && (int)MASKS.Insert)
6
2743
by: Protoman | last post by:
I'm writing a program to calc truth tables of arguments to prove that they are logically valid. Currently, I have to tell the program to print a truth table, and check it by hand to prove it's valid. I'm tired of doing this. I need to write a fn that, given three functions/one function and two variables or anyother combo, run through all four rows, and determine if it's valid. An argument is invalid iff any row has true premises and a...
10
18022
by: Jonathan | last post by:
Hi all, I'm having an argument with a co-worker about the difference between the & and && operators when applied to boolean operands in C#. His point of view is that the expression (false & expr2) might be optimised at JIT-time and the second expression will not be evaluated. In my opinion this would break the contract of the C# language if the JIT compiler were to remove the call to expr2 entirely. I'm not saying that it's good...
9
3748
by: marko | last post by:
/* code start */ int a = 0; /* expected evaluation and excution order with precedence in mind /* False(3) , True(1), False(2) */ if ( (a=1) == 0 || 0 != 1 && (a =2) == 1) putchar('T'); printf("%d", a); /* code end */ 2
10
105194
by: r035198x | last post by:
The Object class has five non final methods namely equals, hashCode, toString, clone, and finalize. These were designed to be overridden according to specific general contracts. Other classes that make use of these methods assume that the methods obey these contracts so it is necessary to ensure that if your classes override these methods, they do so correctly. In this article I'll take a look at the equals and hashCode methods. ...
0
9462
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9287
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10046
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9886
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9857
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9722
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7259
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6542
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5155
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.