Introduction to Object-Oriented Programming in Python
George Boorman
Curriculum Manager, DataCamp
class Customer: def __init__(self, name, balance): self.name, self.balance = name, balance customer1 = Customer("Maryam Azar", 3000) customer2 = Customer("Maryam Azar", 3000)
# Check for equality customer1 == customer2
False
class Customer: def __init__(self, name, balance, acc_id): self.name, self.balance = name, balance self.acc_id = acc_id customer1 = Customer("Maryam Azar", 3000, 123) customer2 = Customer("Maryam Azar", 3000, 123)
customer1 == customer2
False
customer_one = Customer("Maryam Azar", 3000, 123) customer_two = Customer("Maryam Azar", 3000, 123)
print(customer_one)
<__main__.Customer at 0x1f8598e2e48>
print(customer_two)
<__main__.Customer at 0x1f8598e2240>
print()
output refers to the memory chunk that the variable is assigned to==
compares references, not data# Two different lists containing the same data
list_one = [1,2,3]
list_two = [1,2,3]
list_one == list_two
True
__eq__()
is called when 2 objects of a class are compared using ==
self
and other
- objects to compareclass Customer: def __init__(self, acc_id, name): self.acc_id, self.name = acc_id, name
# Will be called when == is used def __eq__(self, other):
# Printout print("__eq__() is called") # Returns True if all attributes match return (self.acc_id == other.acc_id) and (self.name == other.name)
# 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
class Customer:
def __init__(self, acc_id, name):
self.acc_id, self.name = idacc_id name
def __eq__(self, other):
# Returns True if the objects have the same attributes
# and are of the same type
return (self.acc_id == other.acc_id) and (self.name == other.name)\
and (type(self) == type(other))
Operator | Method |
---|---|
== |
__eq__() |
!= |
__ne__() |
>= |
__ge__() |
<= |
__le__() |
> |
__gt__() |
< |
__lt__() |
Introduction to Object-Oriented Programming in Python