15 Mutability 4pp
15 Mutability 4pp
Objects
4
Representing Strings: the ASCII Standard
American Standard Code for Information Interchange
0 0 0
8 rows: 3 bits
0 0 1
0 1 0
Example: Strings 0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
16 columns: 4 bits
http://ian-albert.com/unicode_chart/unichart-chinese.jpg
'⚅' '♪'
LATIN CAPITAL LETTER A
DIE FACE-6
7
Some Objects Can Change Mutation Can Happen Within a Function Call
[Demo] A function can change the value of any object in its scope
First example in the course of an object changing state >>> four = [1, 2, 3, 4] def mystery(s): or def mystery(s):
>>> len(four) s.pop() s[2:] = []
The same object can change in value throughout the course of computation 4 s.pop()
>>> mystery(four)
👶
👧
👩
👵
jessica >>> len(four)
same_person 2
Unicode
OLDER character
WOMAN
BABY
GIRL name >>> four = [1, 2, 3, 4] def another_mystery():
WOMAN
>>> len(four) four.pop()
4 four.pop()
All names that refer to the same object are affected by a mutation >>> another_mystery() # No arguments!
>>> len(four)
Only objects of mutable types can change: lists & dictionaries 2
{Demo}
9 10
pythontutor.com/composingprograms.html#code=def%20mystery%28s%29%3A%0A%20%20%20%20s.pop%28%29%0A%20%20%20%20s.pop%28%29%0A%0Afour%20%3D%20[1,%202,%203,%204]%0Amystery%28four%29&mode=display&origin=composingprograms.js&cumulative=true&py=3&rawInputLstJSON=[]&curInstr=0
• A compound data object has an "identity" in addition to the pieces of which it is composed
Identity A default argument value is part of a function value, not generated by a call
(Demo)
15 16
pythontutor.com/composingprograms.html#code=def%20f%28s%3D[]%29%3A%0A%20%20%20%20s.append%283%29%0A%20%20%20%20return%20len%28s%29%0A%20%20%20%20%0Af%28%29%0Af%28%29%0Af%28%29&mode=display&origin=composingprograms.js&cumulative=true&py=3&rawInputLstJSON=[]&curInstr=0
A Function with Behavior That Varies Over Time
In a (mutable) list
referenced in the parent
>>> withdraw = make_withdraw_list(100) frame of the function
Argument:
Return value: >>> withdraw(25) amount to withdraw
Mutable Functions remaining balance 75
18
withdraw doesn't
reassign any name
within the parent Name bound
outside of
withdraw def
Element
assignment
changes a list
19