Equality comparison between objects #
Let's do a quick equality comparison between two MyStr objects.
sentence1 = MyStr("Hello World!")
sentence2 = MyStr("Hello World!")
print(sentence1 == sentence2) # Output: False
This is not the behavior we want. We want our MyStr objects to return True the same way str objects are equal. For example:
sentence1 = "Hello World"
sentence2 = "Hello World"
print(sentence1 == sentence2) # Output: True
Special method __eq__ #
In the first example in this lesson, the only way equality comparison == will return True is when both objects are the same object.
For example:
sentence1 = MyStr("Hello World!")
print(sentence1 == sentence1) # Output: True
To implement custom equality comparison for our objects, we need to define the special method __eq__ in our class. For example:
class Dog:
def __init__(self, name):
self.name = name
def __eq__(self, other):
return self.name == other.name
dog1 = Dog("Boss")
dog2 = Dog("Boss")
dog3 = Dog("Bingo")
print(dog1 == dog2) # Output: True
print(dog1 == dog3) # Output: False
In the example above, the __eq__ method takes two arguments: the object itself self, and the other object to compare to other. This function is called when == operator is used to compare two objects. The code dog1 == dog2 will call the __eq__ method with dog1 as self, and dog2 as other. If both dogs' names are the same, the method returns True, otherwise it returns False.
Exercise #
- Add the
__eq__method to ourMyStrclass to mimick regular strings.
Tests #
MyStr("Hello World") == MyStr("Hello World")should equal toTrueMyStr("Hello World") == MyStr("Python is awesome")should equal toFalse
Getting Started with Python
Data Types
Python Functions
Statements in Python
Basic Debugging in Python
Basic Algorithm
Object-Oriented Programming
Error Handling
Intermediate Algorithm
Python Modules