<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>learning python &#187; equality</title>
	<atom:link href="http://www.learningpython.com/tag/equality/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.learningpython.com</link>
	<description>one man's journey into python...</description>
	<lastBuildDate>Mon, 26 Apr 2010 01:21:51 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=abc</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Operator Overload! Learn how to change the behavior of equality operators.</title>
		<link>http://www.learningpython.com/2008/06/21/operator-overload-learn-how-to-change-the-behavior-of-equality-operators/</link>
		<comments>http://www.learningpython.com/2008/06/21/operator-overload-learn-how-to-change-the-behavior-of-equality-operators/#comments</comments>
		<pubDate>Sat, 21 Jun 2008 15:21:49 +0000</pubDate>
		<dc:creator>selsine</dc:creator>
				<category><![CDATA[Python Magazine]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[equality]]></category>
		<category><![CDATA[operator]]></category>
		<category><![CDATA[overload]]></category>
		<category><![CDATA[PythonMagazine]]></category>

		<guid isPermaLink="false">http://www.learningpython.com/?p=76</guid>
		<description><![CDATA[
			
				
			
		
By: Mark Mruss
Note: This article was first published the November 2007 issue of Python Magazine
While the equality operator works great on numbers and strings the fact the way it treats your custom objects really is not that useful. This article looks into overloading the equality operator so that you can easily compare your custom classes.

Introduction
Introducing [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.learningpython.com%2F2008%2F06%2F21%2Foperator-overload-learn-how-to-change-the-behavior-of-equality-operators%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.learningpython.com%2F2008%2F06%2F21%2Foperator-overload-learn-how-to-change-the-behavior-of-equality-operators%2F&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p><strong>By: Mark Mruss</strong></p>
<p><strong>Note:</strong> This article was first published the November 2007 issue of <a href="http://www.pythonmagazine.com">Python Magazine</a></p>
<p>While the equality operator works great on numbers and strings the fact the way it treats your custom objects really is not that useful. This article looks into overloading the equality operator so that you can easily compare your custom classes.</p>
<ol>
<li><a href="#Introduction">Introduction</a></li>
<li><a href="#Introducing">Introducing the terms: operators and operator overloading</a></li>
<li><a href="#QuickExample">A Quick Example of the Default Equality Operator</a></li>
<li><a href="#Overloading">Overloading the Equality Operator</a></li>
<li><a href="#NotImplemented">Telling Python that the Comparison has Not Been Implemented</a></li>
<li><a href="#InequalityOperator">The Inequality Operator</a></li>
<li><a href="#Dangers">Dangers</a></li>
<li><a href="#Conclusion">Conclusion</a></li>
</ol>
<p><span id="more-76"></span></p>
<h2><a name="Introduction">Introduction</a></h2>
<p>In my experience as a professional programmer, testing for the equality between two instances of a class is a fairly common task. In other words, you are comparing the data that each class contains and checking whether the data in one class is identical to the data in the other class.</p>
<p>One of the nice features of Python is that it has a default equality operator defined for any custom objects that you create. The unfortunate thing about this default equality operator is that it doesn’t provide the functionality that you expect. This is because the equality operator (==) actually performs an identity comparison, rather than an equivalence test. If you were to run the following code:</p>
<div class="hl-surround" style="height:28px;"><div class="hl-main"><pre><span class="hl-identifier">if </span><span class="hl-brackets">(</span><span class="hl-identifier">object_one</span><span class="hl-code"> == </span><span class="hl-identifier">object_two</span><span class="hl-brackets">)</span><span class="hl-default">:</span></pre></div></div>
<p>By default Python actually compares whether or not <code>object_one</code> <strong>is</strong> <code>object_two</code> (this is the same comparison that can be made using the <code>is</code> keyword) instead of determining whether or not <code>object_one</code> is equivalent to <code>object_two</code>. Fortunately for us, overloading the default equality operator in Python is a relatively easy task. There are, however, some &#8220;gotchas&#8221; and other interesting features of which one should be aware.</p>
<h2><a name="Introducing">Introducing the terms: operators and operator overloading</a></h2>
<p>An operator can be difficult to define, and like many programming definitions, sometimes the definition only serves to confuse the matter further. In general though, you can think of operators as being very similar to the operators that you encountered in Math class, such as: the + operator, the &#8211; operator, and so forth.</p>
<p>In Python the following are operators<a href="#1">[1]</a>:</p>
<pre>
+	-	*	<strong>	/	//	%	<>>	&#038;
|	^	~	<>	< =	>=	==	!=	<>
</strong></pre>
<p>In programming languages we generally encounter binary operators. This means that each operator takes two operands. An operand serves as input to an operator. For example, in the statement:</p>
<div class="hl-surround" style="height:28px;"><div class="hl-main"><pre><span class="hl-number">2</span><span class="hl-default"> + </span><span class="hl-number">6</span></pre></div></div>
<p>+ is a binary operator that takes two operands, 2 and 6 as inputs. Similarly, in this statement:</p>
<div class="hl-surround" style="height:28px;"><div class="hl-main"><pre><span class="hl-identifier">my_value</span><span class="hl-default"> - </span><span class="hl-number">6</span></pre></div></div>
<p>- is an operator that takes two operands, <code>my_value</code> and 6 as inputs.</p>
<p>Operator overloading is a programming term that means taking the default behaviour of an operator and overloading it. That is, changing the default implementation of an operator for a given object. An example of this (although something that you should never do) would be to overload the + operator to actually perform subtraction instead when it is applied to your class. </p>
<h2><a name="QuickExample">A Quick Example of the Default Equality Operator</a></h2>
<p>Now that the definitions are out of the way, let&#8217;s look at an example where one might want to overload the equality operator. For this example I will bring back a favourite example from my Computer Science days: the <code>Student</code> class:</p>
<div class="hl-surround" ><div class="hl-main"><pre><span class="hl-reserved">class </span><span class="hl-identifier">Student</span><span class="hl-brackets">(</span><span class="hl-identifier">object</span><span class="hl-brackets">)</span><span class="hl-default">:

	</span><span class="hl-reserved">def </span><span class="hl-identifier">__init__</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">, </span><span class="hl-identifier">name</span><span class="hl-code">, </span><span class="hl-identifier">student_number</span><span class="hl-brackets">)</span><span class="hl-default">:
		</span><span class="hl-identifier">self</span><span class="hl-default">.</span><span class="hl-identifier">name</span><span class="hl-default"> = </span><span class="hl-identifier">name
		self</span><span class="hl-default">.</span><span class="hl-identifier">student_number</span><span class="hl-default"> = </span><span class="hl-identifier">student_number</span></pre></div></div>
<p>As you can see the <code>Student</code> class has two data members: 1) the student&#8217;s name, and, 2) her student number.</p>
<p>If we run the following code:</p>
<div class="hl-surround" ><div class="hl-main"><pre><span class="hl-identifier">mark</span><span class="hl-default"> = </span><span class="hl-identifier">Student</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">Mark Mruss</span><span class="hl-quotes">&quot;</span><span class="hl-code">, </span><span class="hl-number">067213</span><span class="hl-brackets">)
</span><span class="hl-identifier">guido</span><span class="hl-default"> = </span><span class="hl-identifier">Student</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">Guido van Rossum</span><span class="hl-quotes">&quot;</span><span class="hl-code">, </span><span class="hl-number">000001</span><span class="hl-brackets">)
</span><span class="hl-identifier">if </span><span class="hl-brackets">(</span><span class="hl-identifier">mark</span><span class="hl-code"> == </span><span class="hl-identifier">guido</span><span class="hl-brackets">)</span><span class="hl-default">:
	</span><span class="hl-reserved">print </span><span class="hl-quotes">&quot;</span><span class="hl-string">Equal</span><span class="hl-quotes">&quot;
</span><span class="hl-reserved">else</span><span class="hl-default">:
	</span><span class="hl-reserved">print </span><span class="hl-quotes">&quot;</span><span class="hl-string">Not Equal</span><span class="hl-quotes">&quot;</span></pre></div></div>
<p>&#8220;Not Equal&#8221; will be printed out as you would expect since the two students are clearly not equivalent. But what about this code:</p>
<div class="hl-surround" ><div class="hl-main"><pre><span class="hl-identifier">mark</span><span class="hl-default"> = </span><span class="hl-identifier">Student</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">Mark Mruss</span><span class="hl-quotes">&quot;</span><span class="hl-code">, </span><span class="hl-number">067213</span><span class="hl-brackets">)
</span><span class="hl-identifier">mark_two</span><span class="hl-default"> = </span><span class="hl-identifier">Student</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">Mark Mruss</span><span class="hl-quotes">&quot;</span><span class="hl-code">, </span><span class="hl-number">067213</span><span class="hl-brackets">)
</span><span class="hl-identifier">if </span><span class="hl-brackets">(</span><span class="hl-identifier">mark</span><span class="hl-code"> == </span><span class="hl-identifier">mark_two</span><span class="hl-brackets">)</span><span class="hl-default">:
	</span><span class="hl-reserved">print </span><span class="hl-quotes">&quot;</span><span class="hl-string">Equal</span><span class="hl-quotes">&quot;
</span><span class="hl-reserved">else</span><span class="hl-default">:
	</span><span class="hl-reserved">print </span><span class="hl-quotes">&quot;</span><span class="hl-string">Not Equal</span><span class="hl-quotes">&quot;</span></pre></div></div>
<p>Here, as in the previous example, &#8220;Not Equal&#8221; will be printed out. This is because, as mentioned earlier, the default implementation of the equality operator is to perform an identity comparison. In other words, the default equality operator asks, is <code>mark</code> the same object as <code>mark_two</code>? In Python the equality comparison depends on the type of objects being compared. For custom classes that you or I will create, the equality comparison will perform an identity comparison by comparing the object’s internal id. In other words, it will only result in True if the objects being compared actually <strong>are</strong> each other. For example:</p>
<div class="hl-surround" ><div class="hl-main"><pre><span class="hl-identifier">student_one</span><span class="hl-default"> = </span><span class="hl-identifier">Student</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">Mark Mruss</span><span class="hl-quotes">&quot;</span><span class="hl-code">, </span><span class="hl-number">067213</span><span class="hl-brackets">)
</span><span class="hl-identifier">student_two</span><span class="hl-default"> = </span><span class="hl-identifier">student_one
if </span><span class="hl-brackets">(</span><span class="hl-identifier">student_one</span><span class="hl-code"> == </span><span class="hl-identifier">student_two</span><span class="hl-brackets">)</span><span class="hl-default">:
	</span><span class="hl-reserved">print </span><span class="hl-quotes">&quot;</span><span class="hl-string">Equal</span><span class="hl-quotes">&quot;
</span><span class="hl-reserved">else</span><span class="hl-default">:
	</span><span class="hl-reserved">print </span><span class="hl-quotes">&quot;</span><span class="hl-string">Not Equal</span><span class="hl-quotes">&quot;</span></pre></div></div>
<p>Results in &#8220;Equal&#8221; being printed out, as would:</p>
<div class="hl-surround" ><div class="hl-main"><pre><span class="hl-identifier">student_one</span><span class="hl-default"> = </span><span class="hl-identifier">Student</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">Mark Mruss</span><span class="hl-quotes">&quot;</span><span class="hl-code">, </span><span class="hl-number">067213</span><span class="hl-brackets">)
</span><span class="hl-identifier">student_two</span><span class="hl-default"> = </span><span class="hl-identifier">student_one
if </span><span class="hl-brackets">(</span><span class="hl-builtin">id</span><span class="hl-brackets">(</span><span class="hl-identifier">student_one</span><span class="hl-brackets">)</span><span class="hl-code"> == </span><span class="hl-builtin">id</span><span class="hl-brackets">(</span><span class="hl-identifier">student_two</span><span class="hl-brackets">))</span><span class="hl-default">:
	</span><span class="hl-reserved">print </span><span class="hl-quotes">&quot;</span><span class="hl-string">Equal</span><span class="hl-quotes">&quot;
</span><span class="hl-reserved">else</span><span class="hl-default">:
	</span><span class="hl-reserved">print </span><span class="hl-quotes">&quot;</span><span class="hl-string">Not Equal</span><span class="hl-quotes">&quot;</span></pre></div></div>
<p><strong>Note:</strong> The equality comparison for built-in objects and types like numbers, strings, lists, tuples, and mappings behave differently. Numbers are compared arithmetically. The numerical values of the characters within strings are compared arithmetically. The comparison of lists and tuples is simply a comparison of their inner values, while the comparison of mappings are comparisons of an ordered list of their values.<a href="#2">[2]</a></p>
<h2><a name="Overloading">Overloading the Equality Operator</a></h2>
<p>Hopefully the above example illustrated a case where we might want to overload the equality operator to make it so that the following code:</p>
<div class="hl-surround" ><div class="hl-main"><pre><span class="hl-identifier">student_one</span><span class="hl-default"> = </span><span class="hl-identifier">Student</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">Mark Mruss</span><span class="hl-quotes">&quot;</span><span class="hl-code">, </span><span class="hl-number">067213</span><span class="hl-brackets">)
</span><span class="hl-identifier">student_two</span><span class="hl-default"> = </span><span class="hl-identifier">Student</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">Mark Mruss</span><span class="hl-quotes">&quot;</span><span class="hl-code">, </span><span class="hl-number">067213</span><span class="hl-brackets">)
</span><span class="hl-identifier">if </span><span class="hl-brackets">(</span><span class="hl-identifier">student_one</span><span class="hl-code"> == </span><span class="hl-identifier">student_two</span><span class="hl-brackets">)</span><span class="hl-default">:
	</span><span class="hl-reserved">print </span><span class="hl-quotes">&quot;</span><span class="hl-string">Equal</span><span class="hl-quotes">&quot;
</span><span class="hl-reserved">else</span><span class="hl-default">:
	</span><span class="hl-reserved">print </span><span class="hl-quotes">&quot;</span><span class="hl-string">Not Equal</span><span class="hl-quotes">&quot;</span></pre></div></div>
<p>Would result in &#8220;Equal&#8221; being printed out, i.e. a true equality comparison as opposed to an identity comparison. In order to do this we need to change to the default functionality of the equality operator. In other words we need to overload it.</p>
<p>In general, operator overloading in Python means adding a special function to your class that will perform the function of the operator it is meant to represent. There are two ways in which one can overload the equality operator in Python: 1) the first method is to use the <code>__eq__</code> function, a so-called &#8220;rich comparison&#8221; function. &#8220;Rich comparison&#8221; functions are functions that overload specific comparison operators (i.e. <code>__eq__</code> to overload ==). 2) The second is to use the <code>__cmp__</code> function, which is used to overload all comparison operators if no &#8220;rich comparison&#8221; functions are present.  </p>
<p>Since <code>__cmp__</code> is used to override all comparison operators (<code>==, !=, < , <=, >, >=</code>), I would suggest using the &#8220;rich comparison&#8221; method unless you are using a version of Python that is earlier then version 2.1, or you are convinced that you know what <code>< =</code> means to our </code><code>Student</code> class. Let&#8217;s forget about the <code>__cmp__</code> operator for now and focus on using the &#8220;rich comparison&#8221; functions to overload the equality operator. </p>
<p>&#8220;Rich comparison&#8221; functions can return any value, but you should try to return a value that is, or can be, interpreted as a boolean value. This is important because these functions will often be used in situations where the return value will be used in a boolean comparison. </p>
<p>When using the &#8220;rich comparison&#8221; functions it is important to know which functions are being called internally. For example, when we run:</p>
<div class="hl-surround" style="height:28px;"><div class="hl-main"><pre><span class="hl-identifier">student_one</span><span class="hl-default"> == </span><span class="hl-identifier">student_two</span></pre></div></div>
<p>If <code>__eq__</code> exists in the <code>Student</code> class, the following is actually being called:</p>
<div class="hl-surround" style="height:28px;"><div class="hl-main"><pre><span class="hl-identifier">student_one</span><span class="hl-default">.</span><span class="hl-identifier">__eq__</span><span class="hl-brackets">(</span><span class="hl-identifier">student_two</span><span class="hl-brackets">)</span></pre></div></div>
<p>When we run:</p>
<div class="hl-surround" style="height:28px;"><div class="hl-main"><pre><span class="hl-identifier">student_two</span><span class="hl-default"> == </span><span class="hl-identifier">student_one</span></pre></div></div>
<p>The following is actually called:</p>
<div class="hl-surround" style="height:28px;"><div class="hl-main"><pre><span class="hl-identifier">student_two</span><span class="hl-default">.</span><span class="hl-identifier">__eq__</span><span class="hl-brackets">(</span><span class="hl-identifier">student_one</span><span class="hl-brackets">)</span></pre></div></div>
<p>As you can see it is the operand on the left-hand side whose <code>__eq__</code> function will be called. It is important to note that if the operand on the left-hand side lacks the <code>__eq__</code> function while the operand on the right-hand side has one, the right-hand operand&#8217;s <code>__eq__</code> function will not be called.</p>
<p>Lets start off with a simple, but incorrect, example (the reasons for its incorrectness will be explained below):</p>
<div class="hl-surround" ><div class="hl-main"><pre><span class="hl-reserved">def </span><span class="hl-identifier">__eq__</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">, </span><span class="hl-identifier">other</span><span class="hl-brackets">)</span><span class="hl-default">:
	</span><span class="hl-identifier">return </span><span class="hl-brackets">((</span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">name</span><span class="hl-code"> == </span><span class="hl-identifier">other</span><span class="hl-code">.</span><span class="hl-identifier">name</span><span class="hl-brackets">)
		</span><span class="hl-identifier">and </span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">student_number</span><span class="hl-code"> == </span><span class="hl-identifier">other</span><span class="hl-code">.</span><span class="hl-identifier">student_number</span><span class="hl-brackets">))</span></pre></div></div>
<p>This is very straightforward. In the equality comparison, we simply compare the <code>Student</code> class&#8217; two data members. This performs as expected when we run:</p>
<div class="hl-surround" ><div class="hl-main"><pre><span class="hl-identifier">student_one</span><span class="hl-default"> = </span><span class="hl-identifier">Student</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">Mark Mruss</span><span class="hl-quotes">&quot;</span><span class="hl-code">, </span><span class="hl-number">067213</span><span class="hl-brackets">)
</span><span class="hl-identifier">student_two</span><span class="hl-default"> = </span><span class="hl-identifier">Student</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">Guido van Rossum</span><span class="hl-quotes">&quot;</span><span class="hl-code">, </span><span class="hl-number">000001</span><span class="hl-brackets">)
</span><span class="hl-identifier">student_three</span><span class="hl-default"> = </span><span class="hl-identifier">Student</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">Mark Mruss</span><span class="hl-quotes">&quot;</span><span class="hl-code">, </span><span class="hl-number">000001</span><span class="hl-brackets">)
</span><span class="hl-identifier">print </span><span class="hl-brackets">(</span><span class="hl-identifier">student_one</span><span class="hl-code"> == </span><span class="hl-identifier">student_two</span><span class="hl-brackets">)
</span><span class="hl-identifier">print </span><span class="hl-brackets">(</span><span class="hl-identifier">student_one</span><span class="hl-code"> == </span><span class="hl-identifier">student_three</span><span class="hl-brackets">)</span></pre></div></div>
<p>You get:</p>
<div class="hl-surround" ><div class="hl-main"><pre><span class="hl-reserved">False
True</span></pre></div></div>
<p>But what happens when we introduce the <code>Professor</code> class and try the overloaded equality operator:</p>
<div class="hl-surround" ><div class="hl-main"><pre><span class="hl-reserved">class </span><span class="hl-identifier">Professor</span><span class="hl-brackets">(</span><span class="hl-identifier">object</span><span class="hl-brackets">)</span><span class="hl-default">:

	</span><span class="hl-reserved">def </span><span class="hl-identifier">__init__</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">, </span><span class="hl-identifier">instructor</span><span class="hl-code">, </span><span class="hl-identifier">course</span><span class="hl-brackets">)</span><span class="hl-default">:
		</span><span class="hl-identifier">self</span><span class="hl-default">.</span><span class="hl-identifier">instructor</span><span class="hl-default"> = </span><span class="hl-identifier">instructor
		self</span><span class="hl-default">.</span><span class="hl-identifier">course</span><span class="hl-default"> = </span><span class="hl-identifier">course</span></pre></div></div>
<p>As you can see, the <code>Professor</code> class lacks the <code>name</code> and <code>student_number</code> data members. What happens when we compare an instance of the <code>Professor</code> class with an instance of the <code>Student</code> class?</p>
<div class="hl-surround" ><div class="hl-main"><pre><span class="hl-identifier">guido</span><span class="hl-default"> = </span><span class="hl-identifier">Student</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">Guido van Rossum</span><span class="hl-quotes">&quot;</span><span class="hl-code">, </span><span class="hl-number">000001</span><span class="hl-brackets">)
</span><span class="hl-identifier">rob</span><span class="hl-default"> = </span><span class="hl-identifier">Professor</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">Rob Ward</span><span class="hl-quotes">&quot;</span><span class="hl-code">, </span><span class="hl-quotes">&quot;</span><span class="hl-string">74-300</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">)
</span><span class="hl-identifier">print </span><span class="hl-brackets">(</span><span class="hl-identifier">guido</span><span class="hl-code"> == </span><span class="hl-identifier">rob</span><span class="hl-brackets">)</span></pre></div></div>
<p>It results in something like this:</p>
<div class="hl-surround" ><div class="hl-main"><pre><span class="hl-identifier">File </span><span class="hl-quotes">&quot;</span><span class="hl-string">operators.py</span><span class="hl-quotes">&quot;</span><span class="hl-default">, </span><span class="hl-identifier">line </span><span class="hl-number">10</span><span class="hl-default">, </span><span class="hl-reserved">in </span><span class="hl-identifier">__eq__
    return </span><span class="hl-brackets">((</span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">name</span><span class="hl-code"> == </span><span class="hl-identifier">other</span><span class="hl-code">.</span><span class="hl-identifier">name</span><span class="hl-brackets">)
</span><span class="hl-reserved">AttributeError</span><span class="hl-code">: </span><span class="hl-quotes">'</span><span class="hl-string">Professor</span><span class="hl-quotes">' </span><span class="hl-identifier">object has no attribute </span><span class="hl-quotes">'</span><span class="hl-string">name</span><span class="hl-quotes">'</span></pre></div></div>
<p>The way we are overriding the equality operator is not correct because it automatically assumes that the other object has the <code>name</code> and <code>student_number</code> data members. There are a number of methods to get around this problem, including: 1) using the <code>hasattr</code> function, or 2) using the <code>isinstance</code> function.  Using the <code>hasattr</code> function determines if <code>other</code> has the attributes we are looking for before actually querying them.  <code>hasattr</code> simply tells us if an object has a specific attribute or not. Here is a quick example illustrating how to do this:</p>
<div class="hl-surround" ><div class="hl-main"><pre><span class="hl-reserved">def </span><span class="hl-identifier">__eq__</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">, </span><span class="hl-identifier">other</span><span class="hl-brackets">)</span><span class="hl-default">:
	</span><span class="hl-identifier">if </span><span class="hl-brackets">(</span><span class="hl-builtin">hasattr</span><span class="hl-brackets">(</span><span class="hl-identifier">other</span><span class="hl-code">, </span><span class="hl-quotes">&quot;</span><span class="hl-string">name</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">) </span><span class="hl-reserved">and </span><span class="hl-builtin">hasattr</span><span class="hl-brackets">(</span><span class="hl-identifier">other</span><span class="hl-code">, </span><span class="hl-quotes">&quot;</span><span class="hl-string">student_number</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">))</span><span class="hl-default">:
		</span><span class="hl-identifier">return </span><span class="hl-brackets">((</span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">name</span><span class="hl-code"> == </span><span class="hl-identifier">other</span><span class="hl-code">.</span><span class="hl-identifier">name</span><span class="hl-brackets">)
			</span><span class="hl-identifier">and </span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">student_number</span><span class="hl-code"> == </span><span class="hl-identifier">other</span><span class="hl-code">.</span><span class="hl-identifier">student_number</span><span class="hl-brackets">))
	</span><span class="hl-reserved">else</span><span class="hl-default">:
		</span><span class="hl-reserved">return False</span></pre></div></div>
<p>First, we check to see if <code>other</code> has the <code>name</code> and <code>student_number</code> attributes. If it does, we proceed as normal. If it does not, we simply return false.  When we compare the professor and the student we get &#8220;False&#8221; as expected.</p>
<p>What&#8217;s nice about this method is that we don&#8217;t have to care what type <code>other</code> is. We only care whether or not it contains the attributes we need to compare. However, the drawback to this function is that you have to test for the existence of each attribute. Although this may not always be a big deal, if you are dealing with fifty data members in your classes this can quickly become a pain in the neck.</p>
<p>Another solution to the problem with our first overloading example is to use the <code>isinstance</code> function to make sure that <code>other</code> is an instance of our class type. This has the drawback of forcing <code>other</code> to be the same type as your class. In practice however, I believe this to be more of an advantage than a disadvantage.</p>
<div class="hl-surround" ><div class="hl-main"><pre><span class="hl-reserved">def </span><span class="hl-identifier">__eq__</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">, </span><span class="hl-identifier">other</span><span class="hl-brackets">)</span><span class="hl-default">:
	</span><span class="hl-identifier">if </span><span class="hl-brackets">(</span><span class="hl-builtin">isinstance</span><span class="hl-brackets">(</span><span class="hl-identifier">other</span><span class="hl-code">, </span><span class="hl-identifier">Student</span><span class="hl-brackets">))</span><span class="hl-default">:
		</span><span class="hl-identifier">return </span><span class="hl-brackets">((</span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">name</span><span class="hl-code"> == </span><span class="hl-identifier">other</span><span class="hl-code">.</span><span class="hl-identifier">name</span><span class="hl-brackets">)
			</span><span class="hl-identifier">and </span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">student_number</span><span class="hl-code"> == </span><span class="hl-identifier">other</span><span class="hl-code">.</span><span class="hl-identifier">student_number</span><span class="hl-brackets">))
	</span><span class="hl-reserved">else</span><span class="hl-default">:
		</span><span class="hl-reserved">return False</span></pre></div></div>
<p>The first thing we do is check the variable <code>other</code> to make sure that it is an instance of the <code>Student</code> class.  If it is, we then compare all of the data members in the <code>Student</code> class.  If <code>object</code> is not an instance of the <code>Student</code> class, we return <code>False</code>.</p>
<p>In my opinion, this is the preferred method since knowing that the class is the correct type is often important. The <code>hasattr</code> method seems more appropriate for simple data containers like a &#8220;rect&#8221; or &#8220;vector&#8221; class where you are only interested in three or four data members.</p>
<h2><a name="NotImplemented">Telling Python that the Comparison has Not Been Implemented</a></h2>
<p>Up until this point in time we have been returning <code>False</code> when our <code>__eq__</code> function does not support the type of object passed in as <code>other</code>. While this is acceptable and correct given the Python documentation, it seems to be &#8220;proper&#8221; to actually return <code>NotImplemented</code>.  According to the Python documentation, &#8220;Numeric methods and rich comparison methods may return this value if they do not implement the operation for the operands provided. (The interpreter will then try the reflected operation, or some other fallback, depending on the operator.)&#8221; <a href="#4">[4]</a>Let&#8217;s forget abou In other words, if the left operand returns <code>NotImplemented</code>, Python will attempt to use the right hand operand&#8217;s equality operator. And if that does not exist, Python will fall back to the default equality operator.</p>
<p>We can return <code>NotImplemted</code> from our <code>Student</code> class if the operand passed in is not an instance of the <code>Student</code>:</p>
<div class="hl-surround" ><div class="hl-main"><pre><span class="hl-reserved">def </span><span class="hl-identifier">_eq__</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">, </span><span class="hl-identifier">other</span><span class="hl-brackets">)</span><span class="hl-default">:
	</span><span class="hl-identifier">if </span><span class="hl-brackets">(</span><span class="hl-builtin">isinstance</span><span class="hl-brackets">(</span><span class="hl-identifier">other</span><span class="hl-code">, </span><span class="hl-identifier">Student</span><span class="hl-brackets">))</span><span class="hl-default">:
		</span><span class="hl-identifier">return </span><span class="hl-brackets">((</span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">name</span><span class="hl-code"> == </span><span class="hl-identifier">other</span><span class="hl-code">.</span><span class="hl-identifier">name</span><span class="hl-brackets">)
			</span><span class="hl-identifier">and </span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">student_number</span><span class="hl-code"> == </span><span class="hl-identifier">other</span><span class="hl-code">.</span><span class="hl-identifier">student_number</span><span class="hl-brackets">))
	</span><span class="hl-reserved">else</span><span class="hl-default">:
		</span><span class="hl-reserved">return NotImplemented</span></pre></div></div>
<p>Now if we perform the following comparison:</p>
<div class="hl-surround" ><div class="hl-main"><pre><span class="hl-identifier">guido</span><span class="hl-default"> = </span><span class="hl-identifier">Student</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">Guido van Rossum</span><span class="hl-quotes">&quot;</span><span class="hl-code">, </span><span class="hl-number">000001</span><span class="hl-brackets">)
</span><span class="hl-identifier">rob</span><span class="hl-default"> = </span><span class="hl-identifier">Professor</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">Rob Ward</span><span class="hl-quotes">&quot;</span><span class="hl-code">, </span><span class="hl-quotes">&quot;</span><span class="hl-string">74-300</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">)
</span><span class="hl-reserved">print </span><span class="hl-identifier">guido</span><span class="hl-default"> == </span><span class="hl-identifier">rob</span></pre></div></div>
<p>The first step in the processing will be:</p>
<div class="hl-surround" style="height:28px;"><div class="hl-main"><pre><span class="hl-identifier">guido</span><span class="hl-default">.</span><span class="hl-identifier">__eq__</span><span class="hl-brackets">(</span><span class="hl-identifier">rob</span><span class="hl-brackets">)</span></pre></div></div>
<p>This returns <code>NotImplemented</code>. As a result, the reflected operation is attempted: </p>
<div class="hl-surround" style="height:28px;"><div class="hl-main"><pre><span class="hl-identifier">rob</span><span class="hl-default"> == </span><span class="hl-identifier">guido</span></pre></div></div>
<p>Because the <code>Professor</code> class does not have the equality operator overloaded, the default operation is executed and <code>False</code> is printed out just like we wanted.</p>
<p><code>NotImplemented</code> is useful in because instead of returning <code>False</code>, which means that the two operand are not equivalent, you return a value that says that the comparison between the operands has not been implemented.</p>
<h2><a name="InequalityOperator">The Inequality Operator</a></h2>
<p>Now that we know how to overload the equality operator, it stands to reason that we have the opposite operation, the inequality operator (!=) covered as well. But not so fast. In Python the inequality and equality operators are handled separately, meaning that inequality is not simply the opposite of equality.  This means that whenever you overload the equality operator, you have to be sure to overload the inequality operator as well. If you don&#8217;t you might get some strange results. For example, when we use the current code (without the inequality operator overloaded), the following:</p>
<div class="hl-surround" ><div class="hl-main"><pre><span class="hl-identifier">guido</span><span class="hl-default"> = </span><span class="hl-identifier">Student</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">Guido van Rossum</span><span class="hl-quotes">&quot;</span><span class="hl-code">, </span><span class="hl-number">000001</span><span class="hl-brackets">)
</span><span class="hl-identifier">guido_too</span><span class="hl-default"> = </span><span class="hl-identifier">Student</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">Guido van Rossum</span><span class="hl-quotes">&quot;</span><span class="hl-code">, </span><span class="hl-number">000001</span><span class="hl-brackets">)
</span><span class="hl-reserved">print </span><span class="hl-identifier">guido</span><span class="hl-default"> == </span><span class="hl-identifier">guido_too
</span><span class="hl-reserved">print </span><span class="hl-identifier">guido</span><span class="hl-default"> != </span><span class="hl-identifier">guido_too</span></pre></div></div>
<p>Results in:</p>
<div class="hl-surround" ><div class="hl-main"><pre><span class="hl-reserved">True
True</span></pre></div></div>
<p>In the first comparison the overloaded equality operator is used, and results in <code>True</code> being printed. Because the inequality operator is not overloaded in the second comparison, the default inequality operator is used (the identity comparison). <code>True</code> is printed because <code>guido</code> and <code>guido_too</code> are not the same instances.</p>
<p>Thankfully once you have overloaded the equality operator, overloading the inequality operator is very easy. As a general rule, you have to return the opposite of the equality operator, but because we are working with <code>NotImplemented</code>, we have to do a bit more processing to ensure that we don&#8217;t return <code>False</code> when we really want to return <code>NotImplemented</code>. Here is how we can overload the inequality operator in the <code>Student</code> class:</p>
<div class="hl-surround" ><div class="hl-main"><pre><span class="hl-reserved">def </span><span class="hl-identifier">__ne__</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">, </span><span class="hl-identifier">other</span><span class="hl-brackets">)</span><span class="hl-default">:
	</span><span class="hl-identifier">equal_result</span><span class="hl-default"> = </span><span class="hl-identifier">self</span><span class="hl-default">.</span><span class="hl-identifier">__eq__</span><span class="hl-brackets">(</span><span class="hl-identifier">other</span><span class="hl-brackets">)
	</span><span class="hl-identifier">if </span><span class="hl-brackets">(</span><span class="hl-identifier">equal_result </span><span class="hl-reserved">is not NotImplemented</span><span class="hl-brackets">)</span><span class="hl-default">:
		</span><span class="hl-reserved">return not </span><span class="hl-identifier">equal_result
	</span><span class="hl-reserved">return NotImplemented</span></pre></div></div>
<p>First, we call <code>self.__eq__</code> to test whether or not we are equal to <code>other</code>. We then check to make sure that <code>equal_result</code> is not <code>NotImplemented</code>. If it is not, we know that the equality test was implemented and we can safely return its’ opposite. If the result for the equality comparison was <code>NotImplemented</code>, we return <code>NotImplemented</code> for the inequality comparison.</p>
<p><strong>Note:</strong> It is safe to use the <code>is</code> check on <code>NotImplemented</code> (rather than an <code>isinstance</code> check) because <code>NotImplemented</code> is a singleton, meaning that there is only ever one instance of <code>NotImplemented</code> at anytime.</p>
<h2><a name="Dangers">Dangers</a></h2>
<p>While it may seem like operator overloading should become part of every class that you write, a word of warning is necessary. There is a large school of thought that views operator overloading as a dangerous programming technique. They argue that overloading operators changes the default way that an operator works, and not always correctly. Moreover, instead of overriding the equality operator, one can simply add an <code>is_equal_to</code> function to perform the equality check.</p>
<p>The logic behind this criticism is that when someone is using a class or reading some code that you wrote, they will be unable to tell what the equality operator is doing. For example, if they see:</p>
<div class="hl-surround" ><div class="hl-main"><pre><span class="hl-identifier">value</span><span class="hl-default"> = </span><span class="hl-identifier">MyClass</span><span class="hl-brackets">(</span><span class="hl-number">10</span><span class="hl-brackets">)
</span><span class="hl-identifier">value_two</span><span class="hl-default"> = </span><span class="hl-identifier">MyClass</span><span class="hl-brackets">(</span><span class="hl-number">10</span><span class="hl-brackets">)
</span><span class="hl-reserved">print </span><span class="hl-identifier">value</span><span class="hl-default"> == </span><span class="hl-identifier">value_two</span></pre></div></div>
<p>What gets printed out? True or False?  If “MyClass” overrode the equality operator then True will be printed. However, if the equality operator is not overloaded, the standard Python behaviour of equality will result with False being printed out. </p>
<h2><a name="Conclusion">Conclusion</a></h2>
<p>While it&#8217;s true that overloading the equality operator does change the default way the Python functions, I feel that it&#8217;s generally a safe and beneficial addition to your classes. Especially since unless people know the ins and outs of the equality operator they will generally assume that should work the way it does when you overload it. Like all the decisions that you make when working with Python, context is key.</p>
<p><a name="1">[1]</a> <a href="http://docs.python.org/ref/operators.html">http://docs.python.org/ref/operators.html</a><br />
<a name="2">[2]</a> <a href="http://docs.python.org/ref/comparisons.html">http://docs.python.org/ref/comparisons.html</a><br />
<a name="3">[3]</a> <a href="http://docs.python.org/ref/customization.html">http://docs.python.org/ref/customization.html</a><br />
<a name="4">[4]</a> <a href="http://docs.python.org/ref/types.html">http://docs.python.org/ref/types.html</a></p>
<div style="float:right;margin:0px 0px 0px 0px;"><a href="http://www.google.com/reader/link?url=http://www.learningpython.com/2008/06/21/operator-overload-learn-how-to-change-the-behavior-of-equality-operators/&title=Operator Overload! Learn how to change the behavior of equality operators.&srcTitle=learning python&srcURL=http://www.learningpython.com"target="_blank" rel=""><img border="0" src="http://www.learningpython.com/wp-content/plugins/wp-google-buzz/icon/12.png" style="opacity:1;filter:alpha(opacity=100)" onmouseover="this.style.opacity=0.8;this.filters.alpha.opacity=70" onmouseout="this.style.opacity=1;this.filters.alpha.opacity=100"/> </a></div>]]></content:encoded>
			<wfw:commentRss>http://www.learningpython.com/2008/06/21/operator-overload-learn-how-to-change-the-behavior-of-equality-operators/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
