Chapter3-Integrating With Standard Python PDF
Chapter3-Integrating With Standard Python PDF
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
False
False
print(customer1)
<__main__.Customer at 0x1f8598e2e48>
print(customer2)
<__main__.Customer at 0x1f8598e2240>
array1 == array2
True
!= __ne__()
>= __ge__()
<= __le__()
> __gt__()
< __lt__()
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
<__main__.Customer at 0x1f8598e2240> [1 2 3]
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])
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__()
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'
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
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)
BaseException
+-- Exception
+-- ArithmeticError # <---
| +-- FloatingPointError
| +-- OverflowError
| +-- ZeroDivisionError # <---
+-- TypeError
+-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- RuntimeError
...
+-- SystemExit
...
1 h ps://docs.python.org/3/library/exceptions.html
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
cust