Python __eq__ methodology in Python lets you evaluate two objects utilizing their values. Python offers numerous methods of evaluating or customizing the comparability of two objects.
This publish will educate you methods to use the __eq__ dunder methodology. Read on for particulars.
What Is Python _eq_?
Python__eq__ is a particular methodology outlined in a category that lets you evaluate two objects of that class for equality. When you employ the == operator to match two objects, Python will name the __eq__ methodology on the left facet of the operator to find out if the objects are equal.
This is as a result of objects which are thought of equal (in line with the __eq__ methodology) ought to have the identical hash worth. If two objects are thought of equal however have completely different hash values, this could trigger issues when utilizing the objects as keys in a dictionary or as components in a set.
In Python, the __eq__ methodology and the __cmp__ methodology are each used to outline how objects of a category ought to be in contrast. However, a fast python __eq__ vs __cmp__ verify signifies that the __eq__ methodology is used to outline equality, whereas the __cmp__ methodology is used to outline an ordering of the objects. The __cmp__ methodology was eliminated in Python 3 and was changed by a set of strategies which are used to outline particular comparability operations.
Code Examples
You can use the __eq__ methodology in a number of methods in Python. In this part, you will notice the Python __eq__ instance in motion, which can aid you enhance your Python coding abilities.
It is lots simpler to know this methodology utilizing examples. Suppose you’ve an individual class that holds three situations identify, age, and street_name. You can create the category as follows:
Class particular person:
def _init_(self, identify, age, street_name): self.identify = identify self.age = age self.street_name = street_name |
Suppose you’ve the next situations for this class:
david = Person(‘David’, 25, ‘Main Street’)
mercy = Person(‘Mercy’, 25, ‘Main Street’) |
It is evident that david and mercy objects are completely different. If you wish to validate this, you need to use the equal operator (==). Here is how one can accomplish this:
print(david == mercy) # False |
But since david and mercy objects share the identical age it’s your decision them to be equal. What this implies is you need the expression david == mercy to be true.
To make this doable, that is the place you name the _eq_ methodology utilizing the == operator when evaluating situations in a category. Usually, Python will use ‘is’ operator while you fail to supply a transparent implementation within the _eq_ methodology.
Here is how one can implement the __eq__ on this class instance to return true if two objects share the identical age.
Class particular person:
def _init_(self, identify, age, street_name): self.identify = identify self.age = age self.street_name = street_name Def __eq__(self, different): return self.age == different.age |
If you might be to match the 2 situations with the identical age, the expression will return true. However, if the 2 situations have completely different age values, the equal operator will return false.
Example 1: The Default Behavior of __eq__ Method
The python __eq__ default implementation, which is used to implement the equality operator (==), merely checks for object identification. This implies that two objects are thought of equal provided that they’re the identical object in reminiscence.
If you wish to change the habits of the == operator for situations of your class, you’ll be able to override the __eq__ methodology. Below is an instance of the default habits of the __eq__ methodology:
class MyClass:
def __init__(self, worth): self.worth = worth a = MyClass(10) b = MyClass(10) print(a == b) # False |
In this instance, a and b are two completely different objects, though they’ve the identical worth for the worth attribute. Therefore, the __eq__ methodology returns False when referred to as on a and b.
If you wish to change the habits of the == operator for situations of your class, you need to use the python __eq__ override. Here is how you are able to do this:
class MyClass:
def __init__(self, worth): self.worth = worth def __eq__(self, different): if isinstance(different, MyClass): return self.worth == different.worth return False a = MyClass(10) b = MyClass(10) print(a == b) # True |
Now, the __eq__ methodology returns True when referred to as on a and b, as a result of they each have the identical worth for the worth attribute.
Example 2: How to Correctly Overrides Both the __eq__ And __hash__ Methods
Do you’ve a category that makes use of each __hash__ and __eq__ strategies? Here is an instance of how one can accurately override each the __eq__ and __hash__ strategies in a category:
class MyClass:
def __init__(self, worth): self.worth = worth def __eq__(self, different): if isinstance(different, MyClass): return self.worth == different.worth return False def __hash__(self): return hash(self.worth) a = MyClass(10) b = MyClass(10) print(a == b) # True print(hash(a) == hash(b)) # True |
In this instance, the __eq__ methodology returns True when referred to as on a and b, as a result of they each have the identical worth for the worth attribute.
The __hash__ methodology additionally returns the identical hash worth for each a and b, as a result of they’re thought of equal. This implies that a and b can be utilized as keys in a dictionary or as components in a set with out inflicting any issues.
Example 3: Using __eq__ To Compare Numbers
Suppose you’ve a category by the identify Number that accepts attribute num. It may look one thing like this:
Class Number
def __init__(self, num): self.worth = num def __str__(self): return str(self.worth) |
Next, create an inventory of an object containing numbers with values between 10 and 100 and print every by way of the __str__() methodology. Here is how one can create an inventory of those numbers in Python.
Numbers = [num(i*10) for i in range(1,11)]
print(“[”, end=” “ ) for number in Numbers: print(f”{number}”, end= “”) print(“]”) |
If you run this code, you’ll get an inventory of 10 numbers from 10, 20 to 100. Now, you must create a contemporary object whose worth is 20 to determine if the thing is within the checklist.
ob1 = num(20)
if num in Numbers: print(“True”) else: print(“False”) |
However, when you run this code, the result can be false, though 20 is within the checklist. The purpose is you might be but to outline methods to evaluate the objects of the category to these outlined by the person.
In your class, Python doesn’t perceive methods to evaluate two objects. This is the place the highly effective dunder methodology __eq__ is available in to offer your class further performance.
To evaluate the objects efficiently, you have to implement the __eq__ methodology. When you invoke the expression a==b, Python will routinely launch __eq__. In your instance, you’ll be able to implement this operate as follows:
Class Number
def __init__(self, num): self.worth = num def __eq__(self, different): print(“__eq__ called”) return self.worth == different.worth def __str__(self): return str(self.worth) |
By doing this, you might be letting Python evaluate objects in your class relying on the worth of the attribute. Now, when you attempt to execute the code under the output goes to be true. Here is the entire code for this activity:
class Number:
def __init__(self, worth): self.worth = worth def __eq__(self, different): print(“__eq__ called”) return self.worth == different.worth def __str__(self): return str(self.worth) #create an inventory of numbers numbers =[Number(i*10) for i in range(1,11)] print(“[“, end=” “) for number in numbers: print(f”{number}”, end=” “) print(“]”) #now create a brand new object with 20 as its worth num = Number(20) if num in numbers: print(“True”) else: print(“False”) |
When you run this code, you get the next final result:
[ 10 20 30 40 50 60 70 80 90 100 ]
__eq__ referred to as __eq__ referred to as True |
In this instance, you’ll be able to see that the __eq__ methodology has been referred to as twice for the reason that worth 20 occupies index 1 within the checklist.
Supporting Integer Objects
Now suppose you wish to verify if the worth 10 exists within the checklist. Here is an instance of how one can strive including different objects to match together with your class object.
num0 = 10
if num0 in numbers: print(“True”) else: print(“False”) |
If you strive operating this code, you’ll set off AttributeError: ‘int’ object has no attribute ‘value’. The purpose is you are attempting to match an integer object together with your quantity object. As outlined, the __eq__ methodology within the class quantity doesn’t have int within the attribute worth.
Therefore, to incorporate this, you could add a verify inside the __eq__ methodology. This is how one can accomplish this:
class Number:
def __init__(self, worth): self.worth = worth def __eq__(self, different): print(“__eq__ called”) if isinstance(different, Number): return self.worth == different.worth return self.worth == different def __str__(self): return str(self.worth) |
With this in place, in case the “other” object turns into an occasion within the class, your code can be ready to verify them each utilizing the attribute worth.
It is one in all python __eq__ greatest practices. You will have the ability to consider the worth attribute related to the Number object utilizing the worth of the opposite. Now, when you run the code:
num0 = 10
if num0 in numbers: print(“True”) else: print(“False”) The final result can be: __eq__ referred to as True |
Conclusion
Hopefully, this tutorial has helped you perceive how you need to use the __eq__ methodology in Python. Below is a fast recap of what you’ve discovered:
- The __eq__ methodology is essential for evaluating objects in a category with different entities
- It lets you outline the way you evaluate objects in a category
- To evaluate class objects with different objects, you’ll rely upon the isinstance() operate
At this level, it’s clear that the strategy is highly effective. Therefore, it is best to take time to undergo the python __eq__ documentation to uncover its sensible purposes.