伯克利 CS61A 课堂笔记 11 —— Mutability

news2025/2/21 18:22:04

本系列为加州伯克利大学著名 Python 基础课程 CS61A 的课堂笔记整理,全英文内容,文末附词汇解释。

目录

01 Objects

02 Example: Strings

Ⅰ Representing Strings: the ASCII Standard

Ⅱ Representing Strings: the Unicode Standard

03 Mutation Operations

Ⅰ Some Objects Can Change

Ⅱ Mutation Can Happen Within a Function Call

04 Tuples

05 Mutation

Ⅰ Sameness and Change

Ⅱ Identity Operators

Ⅲ Mutable Default Arguments are Dangerous

06 Mutable Functions

Ⅰ A Function with Behavior That Varies Over Time

Ⅱ Mutable Values & Persistent Local State

附:词汇解释


01 Objects

>> from datetime import date
>>> date
<class datetime.date>

>>> today = date(2025, 2, 20)
>>> today
datetimme.date(2025, 2, 20)
>>> freedom = date(2025, 5, 12)
>>> freedom
datetime.date(2025, 5, 12)

>>> str(freedom - today)
'81 days, 0:00:00'
>>> today.year
2025
>>> today.month
2
>>> today.strftime('%A %B %d')
'Thursday February 20'

Objects represent information, which consist of data and behavior, bundled together to create abstractions.

Objects represent things, but also properties, interactions, & processes.

A type of objects is called a class and classes are first-class values in Python.

Object-oriented programming: A metaphor for organizing large programs; Special syntax that can improve the composition of programs.

In Python, every value is an object: All objects have attributes; A lot of data manipulation happens through object methods; Functions do one thing, while objects do many related things.

02 Example: Strings

>>> s = 'Hello'

#String特有的函数
>>> s.upper()
'HELLO'
>>> s.lower()
'hello'
>>> s.swapcase()
'hELLO'
Ⅰ Representing Strings: the ASCII Standard

American Standard Code for Information Interchange.

Layout was chosen to support sorting by character code.

Row indexed 2-5 are a useful 6-bit (64 element) subset.

Control characters were designed for transmission.

>>> a = 'A'
>>> ord(a)
65
>>> hex(ord(a))
'0x41'

>>> print('\n\n\n') #空三格



>>> print('\a\a\a') #响三声
Ⅱ Representing Strings: the Unicode Standard

109, 000 characters.

93 scripts (organized).

Enumeration of character properties, such as case.

A canonical name for every character.

U+0058 LATIN CAPITAL LETTER X

U+263a WHITE SMILING FACE

U+2639 WHITE FROWNING FACE

>>> from unicodedate import name, lookup
>>> name('A')
'LATIN CAPITAL LETTER A'
>>> name('a')
'LATIN SMALL LETTER A'

>>> lookup('WHITE SMILING FACE')
😊
>>> lookup('SNOWMAN')
⛄
>>> lookup('SOCCER BELL')
⚽
>>> lookup('BABY')
👶
>>> lookup('BABY').encode()
b'\xf0\x9f\x91\9b6

03 Mutation Operations

>>> suits = ['coin', 'string', 'myriad']
>>> original_suits = suits

#删
>>> suits.pop()
>>> suits.remove('string')
>>> suits
['coin']

#增
>>> suits.append('cup')
>>> suits.expend(['sword', 'club'])
>>> suits
['coin', 'cup', 'sword', 'club']

#改
>>> suits[2] = 'spade'
>>> suits[0:2] = ['heart', 'diamond']
>>> suits
['heart', 'diamond', 'spade', 'club']

>>> original_suits
['heart', 'diamond', 'spade', 'club']
Ⅰ Some Objects Can Change

The same object can change in value throughout the course of computation.

All names that refer to the same object are affected by a mutation.

Only objects of mutable types can change: lists & dictionaries.

>>> numerals = {'I': 1, 'v': 5, 'X': 10}
>>> numerals
{'V': 5, 'X': 10; 'I':1}

#查改
>>> numerals['X']
10
>>> numerals.get('X')
10
>>> numerals['X'] = 11
>>> numerals['X']
11
>>> numerals
{'V': 5, 'X': 11, 'I':1}

#增删
>>> numerals['L'] = 50
>>> numerals.pop('X')
11
>>> numerals
{'V': 5, 'I':1, 'L': 50}
Ⅱ Mutation Can Happen Within a Function Call

A function can change the value of any object in its scope.

>>> four = [1, 2, 3, 4]
>>> len(four)
4
>>> mustery(four)
>>> len(four)
2

def mystery(s):
    s.pop()
    s.pop()

def mystery(s):
    s[2:] = []
>>> four = [1, 2, 3, 4]
>>> len(four)
4
>>> another_mystery()
>>> len(four)
2

def another_mystery(s):
    four.pop()
    four.pop()

04 Tuples

#Tuple的精髓在于逗号,而不是小括号
>>> (3, 4, 5, 6)
(3, 4, 5, 6)
>>> 3, 4, 5, 6
(3, 4, 5, 6)

>>> ()
()
>>> tuple()
()
>>> tuple([3, 4, 5, 6])
(3, 4, 5, 6)

>>> 2,
(2,)
>>> (2,)
(2,)
>>> 2
2

>>> (3, 4) + (5, 6)
(3, 4, 5, 6)
>>> 5 in (3, 4, 5)
True
#Dictionary的key中严禁出现list
>>> {(1, 2): 3}
{(1, 2): 3}
>>> {[1, 2]: 3}
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> {(1, [2]): 3}
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

Tuples are Immutable Sequences:

Immutable values are protected from mutation.

>>> turtle = (1, 2, 3)
>>> ooze()
>>> turtle
(1, 2, 3)

>>> turtle = [1, 2, 3]
>>> ooze()
>>> turtle
['Anything could be inside!']

​The value of an expression can change because of changes in names or objects.

​An immutable sequence may still change if it contains a mutable values as an element.

​05 Mutation

Ⅰ Sameness and Change

As long as we never modify objects, a compound object is just the totality of its pieces and a rational number is just its numerator and denominator. But, this view is no longer valid in the presence of change.

A compound data object has an "identity" in addition to the pieces of which it is composed.

A list is still "the same" list even if we change its contents. Conversely, we could have two lists that happen to have the same contents, but are different.

Ⅱ Identity Operators

>>> [10] == [10]
True

>>> a = [10]
>>> b = [10]
>>> a == b
True
>>> a is b
False

>>> a.extend([20, 30])
>>> a
[10, 20, 30]
>>> b
[10]

>>> c = b
>>> c is b
True
>>> c.pop()
>>> c
[]
>>> b
[]
>>> a
[10, 20, 30]
Ⅲ Mutable Default Arguments are Dangerous

A default argument is part of a function value, not generated by a call.

>>> def f(s = []):
...    s.append(5)
...    return len(s)
>>> f()
1
>>> f()
2
>>> f()
3

06 Mutable Functions

Ⅰ A Function with Behavior That Varies Over Time

Let's model a bank account that has a balance of $100.

Ⅱ Mutable Values & Persistent Local State
def make_withdraw_list(balance):
    b = [balance]
    def withdraw(amount):
        if amount < b[0]:
            return 'Insufficient funds'
        b[0] = b[0] - amount
        return b[0]

withdraw = make_withdraw_list(100)
withdraw(25)

附:词汇解释

bundle / ˈbʌnd(ə)l / 捆绑、property 属性、interaction / ˌɪntərˈækʃ(ə)n / 交互、object-oriented /ˈɑːbdʒekt ɔːrientɪd / 面向对象的、metaphor / ˈmetəfər / 象征,比喻、syntax / ˈsɪntæks / 语法、data manipulation / məˌnɪpjuˈleɪʃn / 数据操作、first-class 优秀的,一流的、interchange 信息交换、row 行、column / ˈkɑːləm / 列、tilde / ˈtɪldə / 波浪号、subset / ˈsʌbset / 子集、transmission / trænzˈmɪʃ(ə)n / 传播、bell 钟,铃、upper 上层的、lower 下层的、unicode / ˈjuːnɪˌkoʊd / 统一码、script / skrɪpt /(一种语言的)字母系统,字母表、enumeration / ɪˌnuːməˈreɪʃn / 枚举、canonical / kəˈnɑːnɪkl / 标准的,规范的、frown / fraʊn / 皱眉、Latin / ˈlætn / 拉丁语、mutation / mjuːˈteɪʃ(ə)n / 改变、coin 硬币、myriad / ˈmɪriəd / 一万、line feed [计]换行、suit / suːt / 套装、sword / sɔːrd / 剑、spade / speɪd / 锹,铲、diamond /ˈdaɪəmənd / 钻石、mutable 可变的、scope / skoʊp / 范围,领域、mystery / ˈmɪstəri / 神秘的、numerator / ˈnuːməreɪtər / 分子、denominator / dɪˈnɑːmɪneɪtər / 分母、identity / aɪˈdentəti / 个体、default 默认的、generate 产生,引起、withdraw 提,取、persistent 持续的,反复出现的、insufficient / ˌɪnsəˈfɪʃ(ə)nt / 不充分的、assignment 赋值、balance 余款

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2302057.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

DEX-EE三指灵巧手:扩展AI与机器人研究的边界

DEX-EE三指灵巧手&#xff0c;由Shadow Robot与Google DeepMind合作开发&#xff0c;以其先进技术和设计&#xff0c;正在引领AI与机器人研究的新趋势。其高精度传感器和灵活的机械手指&#xff0c;能够捕捉复杂的环境数据&#xff0c;为强化学习实验提供了可靠支持。 Shadow R…

在ubuntu上用Python的openpyxl模块操作Excel的案例

文章目录 安装模块读取Excel数据库取数匹配数据和更新Excel数据 在Ubuntu系统的环境下基本职能借助Python的openpyxl模块实现对Excel数据的操作。 安装模块 本次需要用到的模块需要提前安装(如果没有的话) pip3 install openpyxl pip3 install pymysql在操作前&#xff0c;需…

【STM32】外部时钟|红外反射光电开关

1.外部时钟 单片机如何对外部触发进行计数&#xff1f;先看一下内部时钟&#xff0c;内部时钟是接在APB1和APB2时钟线上的&#xff0c;APB1,APB2来自stm32单片机内部的脉冲信号&#xff0c;也叫内部时钟。我们用来定时。同样我们可以把外部的信号接入单片机&#xff0c;来对其…

深入了解 DevOps 基础架构:可追溯性的关键作用

在当今竞争激烈的软件环境中&#xff0c;快速交付强大的应用程序至关重要。尽管如此&#xff0c;在不影响质量的情况下保持速度可能是一项艰巨的任务&#xff0c;这就是 DevOps 中的可追溯性发挥作用的地方。通过提供软件开发生命周期 &#xff08;SDLC&#xff09; 的透明视图…

Django+Vue3全栈开发实战:从零搭建博客系统

文章目录 1. 开发环境准备2. 创建Django项目与配置3. 设计数据模型与API4. 使用DRF创建RESTful API5. 创建Vue3项目与配置6. 前端页面开发与组件设计7. 前后端交互与Axios集成8. 项目优化与调试9. 部署上线10. 总结与扩展10.1 项目总结10.1.1 技术栈回顾10.1.2 项目亮点 10.2 扩…

深度学习之图像回归(一)

前言 图像回归任务主要是理解一个最简单的深度学习相关项目的结构&#xff0c;整体的思路&#xff0c;数据集的处理&#xff0c;模型的训练过程和优化处理。 因为深度学习的项目思路是差不多的&#xff0c;主要的区别是对于数据集的处理阶段&#xff0c;之后模型训练有一些小…

解决 Mac 只显示文件大小,不显示目录大小

前言 在使用 mac 的时候总是只显示文件的大小&#xff0c;不显示文件夹的大小&#xff0c;为了解决问题可以开启“计算文件夹”。 步骤 1.进入访达 2.工具栏点击“显示”选项&#xff0c;点击 “查看显示选项” 3.勾选 显示“资源库"文件夹 和 计算所有大小 或者点击…

从零开始学习PX4源码9(部署px4源码到gitee)

目录 文章目录 目录摘要1.gitee上创建仓库1.1 gitee上创建仓库PX4代码仓库1.2 gitee上创建子仓库2.固件在gitee部署过程2.1下载固件到本地2.2切换本地分支2.3修改.gitmodules内容2.4同步子模块仓库地址2.5同步子模块仓库地址更新(下载)子模块3.一级子模块和二级子模块的映射关…

2025年AI数字人大模型+智能家居HA引领未来(开源项目名称:AI Sphere Butler)

介绍 开源项目计划&#xff1a;AI Sphere Butler 打造全方位服务用户生活的AI全能管家——代号**“小粒”**&#xff08;管家名称可以随意自定义&#xff09; GitHub地址&#xff1a;https://github.com/latiaoge/AI-Sphere-Butler 项目名称&#xff1a;AI Sphere Butler&…

UGUI RectTransform的SizeDelta属性

根据已知内容&#xff0c;SizeDelta offsetMax - offsetMin 1.锚点聚拢情况下 输出 那么此时SizeDelta就是UI元素的长宽大小 2. 锚点分散时 引用自此篇文章中的描述 揭秘&#xff01;anchoredPosition的几何意义&#xff01; SizeDelta offsetMax - offsetMin (rectMax…

三甲医院网络架构与安全建设实战

一、设计目标 实现医疗业务网/卫生专网/互联网三网隔离 满足等保2.0三级合规要求 保障PACS影像系统低时延传输 实现医疗物联网统一接入管控 二、全网拓扑架构 三、网络分区与安全设计 IP/VLAN规划表 核心业务配置&#xff08;华为CE6865&#xff09; interface 100G…

机器学习笔记——常用损失函数

大家好&#xff0c;这里是好评笔记&#xff0c;公主号&#xff1a;Goodnote&#xff0c;专栏文章私信限时Free。本笔记介绍机器学习中常见的损失函数和代价函数&#xff0c;各函数的使用场景。 热门专栏 机器学习 机器学习笔记合集 深度学习 深度学习笔记合集 文章目录 热门…

计算机网络:应用层 —— 动态主机配置协议 DHCP

文章目录 什么是 DHCP&#xff1f;DHCP 的产生背景DHCP 的工作过程工作流程地址分配机制 DHCP 中继代理总结 什么是 DHCP&#xff1f; 动态主机配置协议&#xff08;DHCP&#xff0c;Dynamic Host Configuration Protocol&#xff09;是一种网络管理协议&#xff0c;用于自动分…

遥感与GIS在滑坡、泥石流风险普查中的实践技术应用

原文>>> 遥感与GIS在滑坡、泥石流风险普查中的实践技术应用 我国是地质灾害多发国家&#xff0c;地质灾害的发生无论是对于地质环境还是人类生命财产的安全都会带来较大的威胁&#xff0c;因此需要开展地质灾害风险普查。利用遥感&#xff08;RS&#xff09;技术进行地…

Unity性能优化个人经验总结(不定期更新)

字符串 在使用常量或静态变量 Update、LateUpdate、FixedUpdate等每帧调用或调用频率很高的函数内使用字符串时&#xff0c;均使用常量或静态变量处理。 原因解释&#xff1a;除了常量或静态变量的字符串将会在每一次调用时&#xff0c;将会new一个新的字符串&#xff0c;导…

python小项目编程-初级(5、词频统计,6、简单得闹钟)

1、词频统计 统计文本文件中每个单词出现的频率。 实现 import tkinter as tk from tkinter import filedialog, messagebox from collections import Counter import reclass WordFrequencyCounter:def __init__(self, master):self.master masterself.master.title("…

微信小程序(uni)+蓝牙连接+Xprint打印机实现打印功能

1.蓝牙列表实现&#xff0c;蓝牙设备展示&#xff0c;蓝牙连接 <template><view class"container"><view class"container_top"><view class"l">设备名称</view><view class"r">{{state.phoneNam…

Eclipse自动排版快捷键“按了没有用”的解决办法

快捷键按了没有用&#xff0c;通常是因为该快捷键方式被其他软件占用了&#xff0c;即别的软件也设置了这个快捷键&#xff0c;导致你按了之后电脑不知道该响应哪个软件。 解决办法&#xff1a;1.将当前软件的这个快捷键改了&#xff1b;2.找到占用的那个软件&#xff0c;把那…

springboot404-基于Java的校园礼服租赁系统(源码+数据库+纯前后端分离+部署讲解等)

&#x1f495;&#x1f495;作者&#xff1a; 爱笑学姐 &#x1f495;&#x1f495;个人简介&#xff1a;十年Java&#xff0c;Python美女程序员一枚&#xff0c;精通计算机专业前后端各类框架。 &#x1f495;&#x1f495;各类成品Java毕设 。javaweb&#xff0c;ssm&#xf…

PHP支付宝--转账到支付宝账户

官方参考文档&#xff1a; ​https://opendocs.alipay.com/open/62987723_alipay.fund.trans.uni.transfer?sceneca56bca529e64125a2786703c6192d41&pathHash66064890​ 可以使用默认应用&#xff0c;也可以自建新应用&#xff0c;此处以默认应用来讲解【默认应用默认支持…