CS61A-lecture15-Mutation

Mytability

Object

  • Object represent imformation
  • They consist of data and behavior, bundled together to create abstractions
  • Object can represent things, but also properties, interactions, and processes
  • A type of object is called a class; classes first-class values in Python
  • Object-oriented programming:
    • A metaphor for organizing large prograns
    • Special syntax that can imporve the composition of programs, like dot expression
  • In Python, every value is an object

String is an object

Representing strings: the ascii standard

1
ord('a')

Unicode standard

1
2
3
4
from unicodedata import name, lookup
name('A')
lookup('BABY')
lookup('SNOWMAN')

Mutation Operation

不同的名称绑定在同一个object上, 对不同名称的影响都会被反映在同一个object上
list和dictionary是可变object
而且可以在函数中被修改

Tuples is immutable object

1
2
3
4
(1, 2, 3)
1, 2, 3 #also Tuple
tuple()
(2,)

list 不能作为字典的key, tuple可以
the value of an expression can change because of changes in names or objects

1
2
3
4
5
6
7
8
9
10
11
#name change:
x = 2
x + x # 4
x = 4
x + x # 8

#Object mutation:
x = [1, 2]
x + x # [1, 2, 1, 2]
x.append(2)
x + x # [1, 2, 3, 1, 2, 3]

An immutable sequence may still change if it contains a mutable value as an element

1
2
3
s = ([1, 2], 3)
s[0] = 4 #(error)
s[0][0] = 4 #([4], 3)

Mutation

  • 只要我们不修改对象,一个复合对象(例如列表或类实例)可以完全由它的组成部分决定。
  • 在 Python 中,每个对象都有一个独立的 ID(用 id() 函数可以查看)
  • 当我们修改列表的内容时,它的 identity 并没有改变
  • 相反,我们也可能有两个对象,内容一样但 identity 不同

identity & equality

is
if only if they have the same identity

==
if only if they have the same value

Mutable default arguments are dangerous

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

1
2
3
4
5
6
7
8
def f(a=[]):
a.append(1)
return a

f()#1
f()#2
f()#3
# 这些值都是同一个object

Mutable Funciton