Operator
overloading:
comparison
O B J E C T- O R I E N T E D P R O G R A M M I N G I N P Y T H O N
Alex Yarosh
Content Quality Analyst @ DataCamp
Object equality
class Customer:
def __init__(self, name, balance):
[Link], [Link] = 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):
[Link], [Link] = name, balance
[Link] = 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 = [Link]([1,2,3])
array2 = [Link]([1,2,3])
array1 == array2
True
OBJECT-ORIENTED PROGRAMMING IN PYTHON
Overloading __eq__()
class Customer:
def __init__(self, id, name):
[Link], [Link] = id, name
# Will be called when == is used
def __eq__(self, other): __eq__() is called when 2 objects of a
# Diagnostic printout class are compared using ==
print("__eq__() is called")
accepts 2 arguments, self and other -
# Returns True if all attributes match objects to compare
return ([Link] == [Link]) and \
returns a Boolean
([Link] == [Link])
OBJECT-ORIENTED PROGRAMMING IN PYTHON
Comparison of objects
# Two equal objects # Two unequal objects - different ids
customer1 = Customer(123, "Maryam Azar") customer1 = Customer(123, "Maryam Azar")
customer2 = Customer(123, "Maryam Azar") customer2 = Customer(456, "Maryam Azar")
customer1 == customer2 customer1 == customer2
__eq__() is called __eq__() is called
True False
OBJECT-ORIENTED PROGRAMMING IN PYTHON
Other comparison operators
Operator Method __hash__() to use objects as dictionary
keys and in sets
== __eq__()
!= __ne__()
>= __ge__()
<= __le__()
> __gt__()
< __lt__()
OBJECT-ORIENTED PROGRAMMING IN PYTHON
Let's practice!
O B J E C T- O R I E N T E D P R O G R A M M I N G I N P Y T H O N
Operator
overloading: string
representation
O B J E C T- O R I E N T E D P R O G R A M M I N G I N P Y T H O N
Alex Yarosh
Content Quality Analyst @ DataCamp
Printing an object
class Customer:
def __init__(self, name, balance):
[Link], [Link] = name, balance import numpy as np
cust = Customer("Maryam Azar", 3000) arr = [Link]([1,2,3])
print(cust) print(arr)
<__main__.Customer at 0x1f8598e2240> [1 2 3]
OBJECT-ORIENTED PROGRAMMING IN PYTHON
__str__() __repr__()
print(obj) , str(obj) repr(obj) , printing in console
print([Link]([1,2,3])) repr([Link]([1,2,3]))
[1 2 3] array([1,2,3])
str([Link]([1,2,3])) [Link]([1,2,3])
[1 2 3] array([1,2,3])
informal, for end user formal, for developer
string representation reproducible representation
fallback for print()
OBJECT-ORIENTED PROGRAMMING IN PYTHON
Implementation: str
class Customer: cust = Customer("Maryam Azar", 3000)
def __init__(self, name, balance):
[Link], [Link] = name, balance # Will implicitly call __str__()
print(cust)
def __str__(self):
cust_str = """ Customer:
Customer: name: Maryam Azar
name: {name} balance: 3000
balance: {balance}
""".format(name = [Link], \
balance = [Link])
return cust_str
OBJECT-ORIENTED PROGRAMMING IN PYTHON
Implementation: repr
class Customer:
def __init__(self, name, balance):
[Link], [Link] = name, balance
def __repr__(self):
# Notice the '...' around name
return "Customer('{name}', {balance})".format(name = [Link], balance = [Link])
cust = Customer("Maryam Azar", 3000)
cust # <--- # Will implicitly call __repr__()
Customer('Maryam Azar', 3000) # <--- not Customer(Maryam Azar, 3000)
Surround string arguments with quotation marks in the __repr__() output
OBJECT-ORIENTED PROGRAMMING IN PYTHON
Let's practice!
O B J E C T- O R I E N T E D P R O G R A M M I N G I N P Y T H O N
Exceptions
O B J E C T- O R I E N T E D P R O G R A M M I N G I N P Y T H O N
Alex Yarosh
Content Quality Analyst @ DataCamp
a = 1 a = [1,2,3]
a / 0 a[5]
Traceback (most recent call last): Traceback (most recent call last):
File "<stdin>", line 1, in <module> File "<stdin>", line 1, in <module>
1/0 a[5]
ZeroDivisionError: division by zero IndexError: list index out of range
a = 1 a = 1
a + "Hello" a + b
Traceback (most recent call last): Traceback (most recent call last):
File "<stdin>", line 2, in <module> File "<stdin>", line 1, in <module>
a + "Hello" a + b
TypeError: unsupported operand type(s) for +: / NameError: name 'b' is not defined
'int' and 'str'
OBJECT-ORIENTED PROGRAMMING IN PYTHON
Exception handling
Prevent the program from terminating when an exception is raised
try - except - finally :
try:
# Try running some code
except ExceptionNameHere:
# Run this code if ExceptionNameHere happens
except AnotherExceptionHere: #<-- multiple except blocks
# Run this code if AnotherExceptionHere happens
...
finally: #<-- optional
# Run this code no matter what
OBJECT-ORIENTED PROGRAMMING IN PYTHON
Raising exceptions
raise ExceptionNameHere('Error message here')
def make_list_of_ones(length):
if length <= 0:
raise ValueError("Invalid length!") # <--- Will stop the program and raise an error
return [1]*length
make_list_of_ones(-1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
make_list_of_ones(-1)
File "<stdin>", line 3, in make_list_of_ones
raise ValueError("Invalid length!")
ValueError: Invalid length!
OBJECT-ORIENTED PROGRAMMING IN PYTHON
Exceptions are classes
standard exceptions are inherited from BaseException or Exception
BaseException
+-- Exception
+-- ArithmeticError # <---
| +-- FloatingPointError
| +-- OverflowError
| +-- ZeroDivisionError # <---
+-- TypeError
+-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- RuntimeError
...
+-- SystemExit
...
1 [Link]
OBJECT-ORIENTED PROGRAMMING IN PYTHON
Custom exceptions
Inherit from Exception or one of its subclasses
Usually an empty class
class BalanceError(Exception): pass
class Customer:
def __init__(self, name, balance):
if balance < 0 :
raise BalanceError("Balance has to be non-negative!")
else:
[Link], [Link] = name, balance
OBJECT-ORIENTED PROGRAMMING IN PYTHON
cust = Customer("Larry Torres", -100)
Traceback (most recent call last):
File "[Link]", line 11, in <module>
cust = Customer("Larry Torres", -100)
File "[Link]", line 6, in __init__
raise BalanceError("Balance has to be non-negative!")
BalanceError: Balance has to be non-negative!
Exception interrupted the constructor → object not created
cust
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
cust
NameError: name 'cust' is not defined
OBJECT-ORIENTED PROGRAMMING IN PYTHON
Catching custom exceptions
try:
cust = Customer("Larry Torres", -100)
except BalanceError:
cust = Customer("Larry Torres", 0)
OBJECT-ORIENTED PROGRAMMING IN PYTHON
Let's practice!
O B J E C T- O R I E N T E D P R O G R A M M I N G I N P Y T H O N