473,734 Members | 2,511 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Which class's comparison function is called?

For example,

class A:
def __init__(self,a ):
self.a = a
def __eq__(self, other):
return self.a == other.a

class B:
def __init__(self,b ):
self.b = b
def __eq__(self, other):
return self.b == other.b
A(1) == B(1)
---AttributeError: B instance has no attribute a

B(1) == A(1)
---AttributeError: A instance has no attribute b

From the above, it seems that Python always uses the function defined
by the class on the LEFT. However, I don't understand the following then:

A(1) == 3
---AttributeError: 'int' object has no attribute a

3 == A(1)
---AttributeError: 'int' object has no attribute a

Can someone explain this? I expected 3 == A(1) to use the __eq__
function defined for 'int' objects.
Jun 6 '07 #1
2 2121
Try adding the following diagnostic messages to your __eq__ class
definitions, and see if it will dispel the confusion for the four
equality tests you have tried:

class A:
def __init__(self,a ):
self.a = a
def __eq__(self, other):
print "(A) self:%r, other:%r" %(self.__class_ _, other.__class__ )
return self.a == other.a

class B:
def __init__(self,b ):
self.b = b
def __eq__(self, other):
print "(B) self:%r, other:%r" %(self.__class_ _, other.__class__ )
return self.b == other.b

You are correct, Python evaluates the expressions from left to right.
A(1) == B(1)
---AttributeError: B instance has no attribute a
The left instance's __eq__ method is invoked, which says, "is the
value of self.a equal to the value of other.a ?"; and the answer is,
"other has no attribute a to compare with self.a!" so you get an
exception.

B(1) == A(1)
---AttributeError: A instance has no attribute b
Same case as the first, but the instances have switched places...

A(1) == 3
---AttributeError: 'int' object has no attribute a
Same case as the first, but 'other' is now an object of type 'int',
which inherently has no attribute 'a'. A similar effect will manifest
when you will try to do:
B(1) == 3
---AttributeError: 'int' object has no attribute 'b'
3 == A(1)
---AttributeError: 'int' object has no attribute a

Can someone explain this? I expected 3 == A(1) to use the __eq__
function defined for 'int' objects.
This last one is interesting.
The '__eq__' method is not defined for 'int' objects. The '=='
operator tests for value equivalence. As before, the left side is
evaluated first, and evaluates to a simple integer value. No special
methods are called. Now, the right side's value is evaluated. Since
equality is being tested, the right side's __eq__ method is called,
with the (self, other) arguments being (<instance of class A>, 3)
respectively. Since 'int' is the 'other' argument in this case, it
again results in the exception "no attribute 'a' ".
The last of the four tests that you have mentioned is giving you the
trouble, right? Perhaps the solution is to add type-checking to the
__eq__ method?

(untested)
def __eq__(self, other):
if isinstance(othe r, int):
tmp = other
else:
tmp = other.a # (other.b in class B definition)
return self.a == tmp # (self.b in class B definition)

Cheers,
-Basilisk96

Jun 6 '07 #2
On Tue, 05 Jun 2007 19:16:53 -0700, Bill Jackson wrote:

[snip]
From the above, it seems that Python always uses the function defined
by the class on the LEFT. However, I don't understand the following
then:
[snip]

In general, infix operators like + - * etc. will call the appropriate
methods __add__ __sub__ etc. for the class on the LEFT. If the class on
the left doesn't define such a method, the class on the right will be
called with __radd__ __rsub__ etc.

(There are complications -- see here for details:
http://docs.python.org/ref/numeric-types.html )

The rules for comparison functions are a little more complicated, and by
a little I mean a lot. You can start here:

http://docs.python.org/ref/customization.html
The exception to the "try the left operand first, then try the right
operand" rule happens when the left operand is a built-in like int,
float, etc. In that case, if Python called int.__add__ (or whatever the
method was), your class would likely never be called, which makes it hard
for you to over-ride the operator. So Python calls your methods first.

And don't forget that if you are inheriting from object, object will
likely define default rich comparisons that probably don't do what you
expect.


--
Steven.
Jun 6 '07 #3

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

Similar topics

0
2710
by: Phil Powell | last post by:
/*-------------------------------------------------------------------------------------------------------------------------------- Parameters: $formField1: The name of the first array $formField2: The name of the second array $formField1CompareWith: String to use as my comparison basis for first array. Defaults to using $val unless it's 'key' $formField2CompareWith: String to use as my comparison basis for second array. Same default as...
7
1867
by: Ben | last post by:
Hi all, I'm not yet good at thinking the right way in c++ so although I could solve this problem, I'm not sure if they way I'm thinking of is the best way to do it. I need a data type or class or something that can hold either an int, or a float, knows which one it is holding, and will allow me to do comparisons with instances of it without the code which asks for the comparison having to know which one it is. So maybe I could do it...
4
1606
by: titancipher | last post by:
I have a container that I wish to allow the user to specify a custom comparison method very similar to std::less. However, I want it to function more like memcmp (returning -1 0 1), and I want to be able to vary the fields that are compared. The example below shows how I'd like it to fit together. struct fields { fields( int f1, int f2, int f3 ){ m_f = f1; m_f = f2; m_f = f3; }
11
2145
by: David Rasmussen | last post by:
I want to use sort() and supply my own comparison function, like bool lessThan(const S& a, const S& b) { return value(a) < value(b); } and then sort by: sort(a.begin(), a.end(), lessThan);
2
1641
by: Russell Hind | last post by:
I have a delegate which I use to store a current 'state' function (for a statemachine inside a form). __delegate void State_t(const Message_c& Message); I assign to it such as m_State = new State_t(this, StateShutdown); How can I later check which method the State is pointing to? And is
4
9697
by: mflll | last post by:
I am looking into the different techniques of handling arrays of edit boxes in Java Script. The first program below works fine. However, are there better ways of doing this, where the person writing the JavaScript doesn't have to pass the index in the "onChange" event name. I thought that one might be able to use "this.value" or compare this as
9
1356
by: lou zion | last post by:
hey all, i've got a class that A that has a static class member static int MajorMode; it's important that if one instance of the class changes this variable, all instances react immediately. while they'll all see the new value of the variable, how do you get them each to execute a function when MajorMode changes?
3
3680
by: kim.nolsoee | last post by:
Hi I want to use the Dictionary Classs that will load my own class called KeyClass used as TKey. Here is the code: public class Dictionary { public static void Main()
3
1170
by: DragonLord | last post by:
Here is the situation I am inserting rows into a datagridview and then using a function to group similar rows together based on a column. When I call to compare the lastrow with the current row the application passes the information that should be equal. i.e 479 ST-Vieurtur as the "Destination" with the call below: if (!ColumnEqual(LastSourceRow, SourceRow)) When the comparison function is called, a and b look exactly alike but...
0
8776
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,...
1
9236
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
9182
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...
0
8186
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6735
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
6031
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
4550
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...
0
4809
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2724
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.