CP学习笔记(5) - 可变数据

  1. Python3可以使用nonlocal 声明父级框架的变量

  2. Python中可以使用字典将多个函数绑定在同一个函数名上

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)
print(check_balance(a))

posted on 2015-12-12 09:56  Rim99  阅读(163)  评论(0编辑  收藏  举报

导航