def maker(N):
def action(X):
return X ** N
return action
# nonlocal
def maker1(N):
state = 1
def action(X):
nonlocal state
print('%d th call.' % state)
state += 1
return X ** N
return action
# default value
def maker2(N):
class Action:
def __init__(self, state = 1):
self.state = state
def __call__(self, X):
print('%d th call.' % self.state)
self.state += 1
return X ** N
return Action()
# function attribute
def maker3(N):
def action(X):
print('%d th call.' % action.state)
action.state += 1
return X ** N
action.state = 1
return action
# mutable object
def maker4(N):
state = [1]
def action(X):
print('%d th call.' % state[0])
state[0] += 1
return X ** N
return action
f = maker4(2)
g = maker4(3)
print(f(2))
print(f(3))
print(g(2))
python state of nested function
最新推荐文章于 2023-03-22 21:30:00 发布