博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
cs61a Mutable Data 2 学习笔记和补充
阅读量:5335 次
发布时间:2019-06-15

本文共 1334 字,大约阅读时间需要 4 分钟。

CS61A Spring 2018

原文地址:


字典的一个简单应用:模拟银行账户

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 dispatchdef 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)

运行结果:

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

你可能感兴趣的文章
bzoj1048 [HAOI2007]分割矩阵
查看>>
python中的__init__ 、__new__、__call__等内置函数的剖析
查看>>
Java中的编码
查看>>
PKUWC2018 5/6
查看>>
As-If-Serial 理解
查看>>
雷林鹏分享:Redis 简介
查看>>
洛谷P1005 矩阵取数游戏
查看>>
在Silverlight中使用HierarchicalDataTemplate为TreeView实现递归树状结构
查看>>
无线通信基础(一):无线网络演进
查看>>
如何在工作中快速成长?阿里资深架构师给工程师的10个简单技巧
查看>>
WebSocket 时时双向数据,前后端(聊天室)
查看>>
关于python中带下划线的变量和函数 的意义
查看>>
linux清空日志文件内容 (转)
查看>>
安卓第十三天笔记-服务(Service)
查看>>
Servlet接收JSP参数乱码问题解决办法
查看>>
【bzoj5016】[Snoi2017]一个简单的询问 莫队算法
查看>>
Ajax : load()
查看>>
MySQL-EXPLAIN执行计划Extra解释
查看>>
Zookeeper概述
查看>>
Zookeeper一致性级别
查看>>