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

转载于:https://www.cnblogs.com/siucaan/p/9623179.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值