Mutable Function & Growth
10.1 Functions with behavior that changes over time
def make_withdraw(balance):
def withdraw(amount):
nonlocal balance
if amount > balance:
return 'insufficient funds'
balance = balance - amount
return balance
return withdraw
>>> withdraw = make_withdraw(100)
>>> withdraw(10)
90
>>> withdraw(10)
80
nonlocal: first nonlocal frame
nonlocal 注意两个特性:一是不能在local中重复定义:
def f():
def g(x):
nonlocal x
return 2 * x
return g
SyntaxError: name 'x' is parameter and nonlocal
二是不能定义global environment中的变量:
x = 4
def g():
nonlocal x
return 2 * x
SyntaxError: no binding for nonlocal 'x' found
对比没有nonlocal声明
def make_withdraw(balance):
def withdraw(amount):
if amount > balance:
return 'insufficient funds'
new_balance = balance - amount
return new_balance
return withdraw
>>> withdraw = make_withdraw(100)
>>> withdraw(10)
90
>>> withdraw(10)
90
Example:
def f(x):
x = 4
def g(y):
def h(z):
nonlocal x
x = x + 1
return x + y + z
return h
return g
a = f(1)
b = a(2)
total = b(3) + b(4)
Answer: 22
a = f(1): x = 1 → x = 4
b = a(2): y = 2
b(3): z = 3 → x = 4 + 1 → x + y + z = 5 + 2 + 3 = 10
b(4): z = 4 → x = 5 + 1 → x + y + z = 6 + 2 + 4 = 12
total = 22
10. 2 Measuring Growth
Common Patterns
Linear Growth
Logarithmic Growth
Exponential Growth
Example:
Linear Growth → Logarithmic Growth