473,463 Members | 1,512 Online
Bytes | Software Development & Data Engineering Community
Create 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 2108
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(other, 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
by: Phil Powell | last post by:
/*-------------------------------------------------------------------------------------------------------------------------------- Parameters: $formField1: The name of the first array $formField2:...
7
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...
4
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...
11
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
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...
4
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...
9
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...
3
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
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...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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,...
0
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...
0
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...
0
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...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

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.