Oct 11-15, 2021 Vikrant Patil
These notes are available online at https://notes.pipal.in/2021/arcesium_finop_batch2/
© Pipal Academy LLP
We will be using jupyter hub from https://lab2.pipal.in for this training.
create a notebook with name module2-day3
def csvparse(filename):
with open(filename) as f:
return [line.strip().split(",") for line in f if line.strip()]
%%file data.csv
1,2,3,4
2,3,4,5
Overwriting data.csv
csvparse("data.csv")
[['1', '2', '3', '4'], ['2', '3', '4', '5']]
# any empty list, dict, set, string or integer with value 0 results in false in if/elif
l = []
s = ""
d = {}
s = set()
n = 0
if l: # false
print("will never reach here")
person = {"name": "Vikrant",
"languages": ["Marathi","English", "Hindi"],
"state": "Maharashtra"}
person
{'name': 'Vikrant', 'language': 'Marathi', 'state': 'Maharashtra'}
def langunage_of_instruction(person):
program_languages = ["English", "Spanish"]
for l in person['languages']:
if l in program_languages:
return {"ID": create_ID(person),
"language": l}
return {"ID": create_ID(person),
"language": "English"}
def langunage_of_instruction_(name, languages, state):
program_languages = ["English", "Spanish"]
for l in person['languages']:
if l in program_languages:
return {"ID": create_ID(name, state),
"language": l}
return {"ID": create_ID(person),
"language": "English"}
numbers = [1, 2, 3, 4, 5]
numbers[0] # method to access
1
numbers.count(2) # method to count!
1
5 in numbers # method to check membership
True
Lets try to model bankaccount using this concept
%%file bank0.py
balance = 100
def get_balance():
return balance # if the variable you want to read, is not available locally read from global!
def deposite(amount):
global balance # don't create local variable
balance = balance + amount
def withdraw(amount):
global balance
balance -= amount
Overwriting bank0.py
import bank0
bank0.get_balance()
100
bank0.deposite(10000)
bank0.get_balance()
10100
bank0.withdraw(400)
bank0.get_balance()
9700
%%file bank1.py
def create_account(balance):
return {"balance": balance} # a dictionary which has balance inside it
def get_balance(account):
return account['balance']
def deposite(account, amount):
account['balance'] +=amount
def withdraw(account, amount):
account['balance'] -= amount
Overwriting bank1.py
import bank1
a1 = bank1.create_account(100)
a2 = bank1.create_account(200)
bank1.get_balance(a1)
100
bank1.get_balance(a2)
200
bank1.deposite(a1, 10000)
bank1.deposite(a2, 5000)
bank1.get_balance(a1)
10100
bank1.get_balance(a2)
5200
bank1.withdraw(a1, 456)
bank1.get_balance(a1)
9644
bank1.get_balance(a2)
5200
%%file bank1.py
def create_account(balance):
return {"balance": balance} # a dictionary which has balance inside it
def get_balance(account):
return account['balance']
def deposite(account, amount):
account['balance'] +=amount
def withdraw(account, amount):
account['balance'] -= amount
Overwriting bank1.py
class BankAccount:
def __init__(self, balance): #dunder init, all dunder are python's magical indetification marks
self.balance = balance
def get_balance(self):
return self.balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
self.balance -= amount
b1 = BankAccount(500)# call class as a function and pass all the arguments given in __init__ except self
b1.get_balance()
500
b1.deposit(5000)
b1.get_balance()
5500
b1.withdraw(300)
b2 = BankAccount(60000)
b2.withdraw(2323)
b2.get_balance()
57677
"hello".startswith("h")
True
nums = [1, 2, 3, 4, 5]
nums[0] # __getitem__
1
nums.__getitem__(0)
1
BankAccount(100)
BankAccount.__init__(100) # self is missing
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-73-9618d5fe0e59> in <module> 1 BankAccount(100) ----> 2 BankAccount.__init__(100) TypeError: __init__() missing 1 required positional argument: 'balance'
class BankAccount:
def __init__(self, balance): #dunder init, all dunder are python's magical indetification marks
self.accountno = id(self) # some mechanism to get unique number for this instance
self.balance = balance
def get_balance(self):
return self.balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
self.balance -= amount
b2 = BankAccount(500)
b2
<__main__.BankAccount at 0x7f52b38d6640>
l = [1, 1, 1]
l
[1, 1, 1]
class BankAccount:
def __init__(self, balance): #dunder init, all dunder are python's magical indetification marks
self.accountno = id(self) # some mechanism to get unique number for this instance
self.balance = balance
def get_balance(self):
return self.balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
self.balance -= amount
def __repr__(self):
return f"BankAccount<{self.accountno}>"
def __str__(self):
return f"BankAccount<{self.accountno} - {self.balance}>"
def __myown__(self): # this is magic method recognised python... so it just another user defined methods
print("Hello")
BankAccount(600)
BankAccount<139993175654016>
b2 = BankAccount(800)
b2
BankAccount<139993175651712>
print(b2)
BankAccount<139993175651712 - 800>
str(b2)
'BankAccount<139993175651712 - 800>'
str(45)
'45'
4 + 5
9
"ytytre" + "uyiu" # __add__
'ytytreuyiu'
"hello" - "hel" # __sub__ not implemented by str class
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-100-d8a5c81ef890> in <module> ----> 1 "hello" - "hel" # __sub__ not implemented by str class TypeError: unsupported operand type(s) for -: 'str' and 'str'
class Light:
def __init__(self):
self.on = False
def switchon(self):
self.on = True
def switchoff(self):
self.on = False
def is_on(self):
return self.on
def __repr__(self):
states = {False:"OFF", True:"ON"}
s = states[self.on]
return f"Light<{s}>"
l1 = Light()
l2 = Light()
l3 = Light()
l1.is_on()
False
l1
Light<OFF>
l2
Light<OFF>
lights = [Light(), Light(), Light(), Light()]
lights
[Light<OFF>, Light<OFF>, Light<OFF>, Light<OFF>]
lights[-1].switchon()
lights
[Light<OFF>, Light<OFF>, Light<OFF>, Light<ON>]
def switchoffall(lights):
for light in lights:
light.switchoff()
lights
[Light<OFF>, Light<OFF>, Light<OFF>, Light<ON>]
lights[0].switchon()
lights
[Light<ON>, Light<OFF>, Light<OFF>, Light<ON>]
switchoffall(lights)
lights
[Light<OFF>, Light<OFF>, Light<OFF>, Light<OFF>]
class WhiteLight(Light): # WhiteLight is sub/chid class of parent class Light
color = "White"
def __repr__(self):
states = {False:"OFF", True:"ON"}
s = states[self.on]
return f"WhiteLight<{s}>"
WhiteLight()
WhiteLight<OFF>
w = WhiteLight()
w # this is internally calling __repr__
WhiteLight<OFF>
w.switchon()
w
WhiteLight<ON>
w.switchoff()
w
WhiteLight<OFF>
w.color
'White'
WhiteLight
__main__.WhiteLight
w
WhiteLight<OFF>
type(w) # this is instance
__main__.WhiteLight
type(WhiteLight) # its a class
type
w.color
'White'
w2 = WhiteLight()
w2.color
'White'
w
WhiteLight<OFF>
w2.switchon()
w2
WhiteLight<ON>
w2.color
'White'
WhiteLight.color = "dullwhite" # class variables..stored with class
w.color
'dullwhite'
w2.color
'dullwhite'
w.on # instance variables... stored wit instance
False
w2.on
True
problem
BeverageVendingMachine. it should have interface to dispnse 100ml beverage and a method to refill. class Dummy:
pass
d = Dummy() #? __init__