Python Program to Differentiate String == operator and__eq__() method

In Python, the comparison operator == and __eq__() method are closely related but serve different purposes when working with strings and objects. The == operator provides default comparison behavior, while __eq__() allows custom equality logic. Understanding their differences is crucial for effective string comparison in data analysis and object-oriented programming.

== Operator in Python

The == operator is used to compare two values for equality. It returns True when values are equal and False when they differ. For strings, it compares content regardless of memory location ?

str1 = "Hello World"
str2 = "Hello World"
str3 = "hello world"

print(f"str1 == str2: {str1 == str2}")
print(f"str1 == str3: {str1 == str3}")
print(f"Memory locations same: {id(str1) == id(str2)}")
str1 == str2: True
str1 == str3: False
Memory locations same: True

__eq__() Method in Python

The __eq__() method defines custom equality behavior for objects. It takes two arguments: self (left operand) and other (right operand). When you use ==, Python internally calls __eq__() ?

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __eq__(self, other):
        if isinstance(other, Person):
            return self.name == other.name and self.age == other.age
        return False

p1 = Person("John", 30)
p2 = Person("John", 30)
p3 = Person("Jane", 25)

print(f"p1 == p2: {p1 == p2}")
print(f"p1 == p3: {p1 == p3}")
print(f"Direct __eq__ call: {p1.__eq__(p2)}")
p1 == p2: True
p1 == p3: False
Direct __eq__ call: True

String Class __eq__() Method

Python strings have a built-in __eq__() method. When you use == with strings, it calls this method internally ?

text1 = "Python"
text2 = "Python"

# These are equivalent
print(f"Using == operator: {text1 == text2}")
print(f"Using __eq__ method: {text1.__eq__(text2)}")

# Demonstrating the relationship
print(f"type(text1.__eq__(text2)): {type(text1.__eq__(text2))}")
Using == operator: True
Using __eq__ method: True
type(text1.__eq__(text2)): <class 'bool'>

Key Differences

Aspect == Operator __eq__() Method
Usage Direct comparison syntax Method call (usually internal)
Customization Uses existing __eq__ implementation Can be overridden for custom logic
Readability Clean, intuitive syntax Explicit method call
Performance Optimized by Python interpreter Direct method invocation

Practical Example with Custom String Comparison

Here's a case-insensitive string comparison using custom __eq__() ?

class CaseInsensitiveString:
    def __init__(self, text):
        self.text = text

    def __eq__(self, other):
        if isinstance(other, CaseInsensitiveString):
            return self.text.lower() == other.text.lower()
        elif isinstance(other, str):
            return self.text.lower() == other.lower()
        return False

    def __repr__(self):
        return f"CaseInsensitiveString('{self.text}')"

s1 = CaseInsensitiveString("Hello")
s2 = CaseInsensitiveString("HELLO")
s3 = "hello"

print(f"s1 == s2: {s1 == s2}")
print(f"s1 == s3: {s1 == s3}")
print(f"Regular strings: {'Hello' == 'HELLO'}")
s1 == s2: True
s1 == s3: True
Regular strings: False

Conclusion

The == operator provides convenient syntax for equality comparison, while __eq__() defines the underlying comparison logic. For strings, both achieve the same result since == internally calls the string's __eq__() method. Understanding this relationship helps in creating custom classes with meaningful equality behavior.

Updated on: 2026-03-27T01:09:06+05:30

400 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements