cs61a Mutable Data 2 学习笔记和补充
CS61A Spring 2018
原文地址:http://composingprograms.com/pages/24-mutable-data.html
字典的一个简单应用:模拟银行账户
def account(initial_balance):
def deposit(amount):
dispatch['balance'] += amount
return dispatch['balance']
def withdraw(amount):
if amount > dispatch['balance']:
return 'Insufficient funds'
dispatch['balance'] -= amount
return dispatch['balance']
dispatch = {'deposit': deposit,
'withdraw': withdraw,
'balance': initial_balance}
return dispatch
def withdraw(account, amount):
return account['withdraw'](amount)
def deposit(account, amount):
return account['deposit'](amount)
def check_balance(account):
return account['balance']
a = account(20)
deposit(a, 5)
withdraw(a, 17)
check_balance(a)
By storing the balance in the dispatch dictionary rather than in the account frame directly, we avoid the need for nonlocal statements in deposit and withdraw.
Local state
Lists and dictionaries have local state, the word “state” implies an evolving process.
nonlocal statements
it’s critical to understand that all instances of a name must refer to the same frame.
Two bindings for the name balance in two different frames, and each withdraw function has a different parent.

浙公网安备 33010602011771号