Operator overloading: comparison

Object-Oriented Programming in Python

Alex Yarosh

Content Quality Analyst @ DataCamp

Object equality

class Customer:
  def __init__(self, name, balance):
    self.name, self.balance = name, balance  


customer1 = Customer("Maryam Azar", 3000)
customer2 = Customer("Maryam Azar", 3000)

customer1 == customer2
False
Object-Oriented Programming in Python

Object equality

class Customer:
  def __init__(self, name, balance, id):
    self.name, self.balance = name, balance
    self.id = id    

customer1 = Customer("Maryam Azar", 3000, 123)
customer2 = Customer("Maryam Azar", 3000, 123)
customer1 == customer2
False
Object-Oriented Programming in Python

Variables are references

customer1 = Customer("Maryam Azar", 3000, 123)
customer2 = Customer("Maryam Azar", 3000, 123)
print(customer1)
<__main__.Customer at 0x1f8598e2e48>
print(customer2)
<__main__.Customer at 0x1f8598e2240>
Object-Oriented Programming in Python

Custom comparison

import numpy as np

# Two different arrays containing the same data
array1 = np.array([1,2,3])
array2 = np.array([1,2,3])

array1 == array2
True
Object-Oriented Programming in Python

Overloading __eq__()

class Customer:
  def __init__(self, id, name):
    self.id, self.name = id, name

# Will be called when == is used def __eq__(self, other):
# Diagnostic printout print("__eq__() is called") # Returns True if all attributes match return (self.id == other.id) and \ (self.name == other.name)

 

 

  • __eq__() is called when 2 objects of a class are compared using ==
  • accepts 2 arguments, self and other - objects to compare
  • returns a Boolean
Object-Oriented Programming in Python

Comparison of objects

# Two equal objects

customer1 = Customer(123, "Maryam Azar")
customer2 = Customer(123, "Maryam Azar")

customer1 == customer2
__eq__() is called
True
# Two unequal objects - different ids

customer1 = Customer(123, "Maryam Azar")
customer2 = Customer(456, "Maryam Azar")

customer1 == customer2
__eq__() is called
False
Object-Oriented Programming in Python

Other comparison operators

Operator Method
== __eq__()
!= __ne__()
>= __ge__()
<= __le__()
> __gt__()
< __lt__()
  • __hash__() to use objects as dictionary keys and in sets
Object-Oriented Programming in Python

Let's practice!

Object-Oriented Programming in Python

Preparing Video For Download...