Lecture 13
Non-Local Assignment & Persistent Local State
def make_withdraw(balance):
def withdraw(amount):
nonlocal balance
if amount > balance:
return "Insufficient funds"
balance = balance - amount
return balance
return withdraw
Reference Transparency
def f(x):
x = 4
def g(y):
def h(z):
nonlocal x
x = x + 1
return x + y + z
return h
return g
>>> a = f(1)
>>> b = a(2)
>>> total = b(3) + b(4)
>>> total
22
计算b(3)时nonlocal x = 4,所以x + 1 = 5, 计算b(4)时调用x时x为5,此时 x + 1 = 6
Lecture 14
Object-Oriented Programming
Object Construction
class Account:
def __init__(self, account_holder):
self.balance = 0
self.holder = account_holder
>>> a = Account('Zhou')
>>> a.balance
0
>>> a.holder
'Zhou'
Methods
class Account:
interest = 0.02 # A class attribute
def __init__(self, account_holder):
self.balance = 0
self.holder = account_holder
def deposit(self, amount):
self.balance += amount
return self.balance
def withdraw(self, amount):
if amount > self.balance:
return "Insufficient funds"
self.balance -= amount
return self.balance
Lecture 15
Inheritance
class CheckingAccount(Account):
interest = 0.01
withdraw_fee = 1
def withdraw(amount):
return Account.withdraw(self, self.amount + withdraw_fee)
Multiple Inheritance
class SavingAccount(Account):
deposit_fee = 2
def deposit(amount):
return Account.deposit(self, self.amount - deposit_fee)
class BestAccount(CheckingAccount, SavingAccount):
def __init__(self, account_holder):
self.balance = 1
self.holder = account_holder
Composition
class Bank:
def __init__(self):
self.accounts = [] # composition
def open_account(self, holder, amount, account_type=Account):
account = account_type(holder)
account.deposit(amount)
self.accounts.append(account)
return account
def pay_interest(self):
for account in self.accounts:
account.deposit(account.balance * account.interest)
Lecture 16