本系列为加州伯克利大学著名 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 余款