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.

猜你喜欢

转载自blog.csdn.net/qq_23869697/article/details/80518993