UCB CS61A--Part II

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)時調(diào)用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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 早安哦天氣是極好的愿你忘記昨天上司的不滿同事的抱怨因下雨灌滿水的地鐵站穿著恨天高穿越在人潮中的酸痛今天啊你會收獲上...
    回應(yīng)閱讀 490評論 0 1
  • 兒子昨晚一回到家,便興高采烈地告訴我說作業(yè)在學(xué)校寫得差不多了,只剩英語與數(shù)學(xué)一小部分了。我提出作業(yè)要給我簽名,人家...
    一沙一世界daisy閱讀 149評論 3 1
  • ????????????????????????????????????????????????? ???...
    正在遺忘你閱讀 414評論 1 1
  • 如果你剛?cè)肼?,你一定有深刻的體會,新員工培訓(xùn)時,所有的講師給的建議都不會逃脫一條:和你的導(dǎo)師打好關(guān)系,多和他吃吃飯...
    老抓閱讀 545評論 1 6

友情鏈接更多精彩內(nèi)容