Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
25 views

Chapter3-Integrating With Standard Python PDF

The document discusses operator overloading in Python, specifically for comparison operators. It shows how to overload the equality operator __eq__() to define object equality. By default, two objects are not equal even if they have the same attributes. To change this, the __eq__() method compares the object's attributes and returns True if they match. This allows defining what makes two objects equal. The document also covers overloading other comparison operators and string representations using __str__() and __repr__().
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Chapter3-Integrating With Standard Python PDF

The document discusses operator overloading in Python, specifically for comparison operators. It shows how to overload the equality operator __eq__() to define object equality. By default, two objects are not equal even if they have the same attributes. To change this, the __eq__() method compares the object's attributes and returns True if they match. This allows defining what makes two objects equal. The document also covers overloading other comparison operators and string representations using __str__() and __repr__().
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

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): __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 (self.id == other.id) and \
returns a Boolean
(self.name == other.name)

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!
OBJECT-ORIENTED PROGRAMMING IN PYTHON
Operator
overloading: string
representation
OBJECT-ORIENTED PROGRAMMING IN PYTHON

Alex Yarosh
Content Quality Analyst @ DataCamp
Printing an object
class Customer:
def __init__(self, name, balance):
self.name, self.balance = name, balance import numpy as np

cust = Customer("Maryam Azar", 3000) arr = np.array([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(np.array([1,2,3])) repr(np.array([1,2,3]))

[1 2 3] array([1,2,3])

str(np.array([1,2,3])) np.array([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):
self.name, self.balance = 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 = self.name, \
balance = self.balance)
return cust_str

OBJECT-ORIENTED PROGRAMMING IN PYTHON


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

def __repr__(self):
# Notice the '...' around name
return "Customer('{name}', {balance})".format(name = self.name, balance = self.balance)
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!
OBJECT-ORIENTED PROGRAMMING IN PYTHON
Exceptions
OBJECT-ORIENTED PROGRAMMING IN PYTHON

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 h ps://docs.python.org/3/library/exceptions.html

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:
self.name, self.balance = name, balance

OBJECT-ORIENTED PROGRAMMING IN PYTHON


cust = Customer("Larry Torres", -100)

Traceback (most recent call last):


File "script.py", line 11, in <module>
cust = Customer("Larry Torres", -100)
File "script.py", 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!
OBJECT-ORIENTED PROGRAMMING IN PYTHON

You might also like