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)

运行结果:https://goo.gl/U7Es3D
implementing—dictionary

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

nonlocal
nonlocal_0
nonlocal0
nonlocal1
nonlocal2

it’s critical to understand that all instances of a name must refer to the same frame.
nonlocal——error
instance_and_frame

Two bindings for the name balance in two different frames, and each withdraw function has a different parent.
nonlocal

use a list instead of nonlocal assignment

multable value

Multiple Mutable Functions

function

posted @ 2018-05-31 09:09  Siucaan  阅读(210)  评论(0)    收藏  举报