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

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

目录

[01 Objects](#01 Objects)

[02 Example: Strings](#02 Example: Strings)

[Ⅰ Representing Strings: the ASCII Standard](#Ⅰ Representing Strings: the ASCII Standard)

[Ⅱ Representing Strings: the Unicode Standard](#Ⅱ Representing Strings: the Unicode Standard)

[03 Mutation Operations](#03 Mutation Operations)

[Ⅰ Some Objects Can Change](#Ⅰ Some Objects Can Change)

[Ⅱ Mutation Can Happen Within a Function Call](#Ⅱ Mutation Can Happen Within a Function Call)

[04 Tuples](#04 Tuples)

[05 Mutation](#05 Mutation)

[Ⅰ Sameness and Change](#Ⅰ Sameness and Change)

[Ⅱ Identity Operators](#Ⅱ Identity Operators)

[Ⅲ Mutable Default Arguments are Dangerous](#Ⅲ Mutable Default Arguments are Dangerous)

[06 Mutable Functions](#06 Mutable Functions)

[Ⅰ A Function with Behavior That Varies Over Time](#Ⅰ A Function with Behavior That Varies Over Time)

[Ⅱ Mutable Values & Persistent Local State](#Ⅱ Mutable Values & Persistent Local State)

附:词汇解释


01 Objects

python 复制代码
>> 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 representinformation, 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

python 复制代码
>>> 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.

python 复制代码
>>> 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

python 复制代码
>>> 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

python 复制代码
>>> 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.

python 复制代码
>>> 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.

python 复制代码
>>> 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:] = []
python 复制代码
>>> four = [1, 2, 3, 4]
>>> len(four)
4
>>> another_mystery()
>>> len(four)
2

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

04 Tuples

python 复制代码
#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
python 复制代码
#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.

python 复制代码
>>> 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
python 复制代码
>>> [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.

python 复制代码
>>> 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
python 复制代码
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 余款

相关推荐
镰圈量化23 分钟前
当电脑上有几个python版本Vscode选择特定版本python
开发语言·vscode·python
宇寒风暖26 分钟前
侯捷 C++ 课程学习笔记:内存管理与工具应用
c++·笔记·学习
宇努力学习33 分钟前
如何本地部署seepseek
python·ai·ollama·deepseek
云缘若仙38 分钟前
directx12 3d+vs2022游戏开发第六章 笔记十一
笔记·directx12 3d
橙狮科技40 分钟前
使用 GPTQ 进行 4 位 LLM 量化
人工智能·python·语言模型
开开心心就好1 小时前
娱乐使用,可以生成转账、图片、聊天等对话内容
windows·python·智能手机·软件工程·娱乐·软件需求
愚昧之山绝望之谷开悟之坡1 小时前
ragflow-RAPTOR到底是什么?请通俗的解释!
python
背太阳的牧羊人1 小时前
RAG检索中使用一个 长上下文重排序器(Long Context Reorder) 对检索到的文档进行进一步的处理和排序,优化输出顺序
开发语言·人工智能·python·langchain·rag
电棍2331 小时前
在wsl环境中配置和开发verilog(一种比较新颖的verilog开发指南)
笔记
007_rbq1 小时前
XUnity.AutoTranslator-Gemini——调用Google的Gemini API, 实现Unity游戏中日文文本的自动翻译
人工智能·python·游戏·机器学习·unity·github·机器翻译