# Example 1
def f1_out(s):
x = 10 # 外部环境的变量
def f2_in(): # 内部函数 该内部函数被认为是一个闭包
print(x * s)
return x * s
# 注意返回的是 函数名 这里是函数地址
# 返回的是 函数名() 则返回该函数的值
return f2_in()
# 就是当某个函数被当成对象返回时,夹带了外部变量,就形成了一个闭包。
# 闭包 :内部函数+定义函数时的环境
f = f1_out(100)
# 1000
# Example 2
def who(name):
def do(what):
print(name, 'say:', what)
return do
# 这里的do 可以理解为变量 每次给do 赋不同的值
# 下面就可以直接用该值作为变量名 给该变量指定动作
lucy = who('lucy')
lucy("About the question ,could u give me some advices?")
john = who('john')
john('I have no idea, I zoned out at the class')
# lucy say: About the question ,could u give me some advices?
# john say: I have no idea, I zoned out at the class
# Example 3
def name(className):
def schedle(time):
print(className, 'will take at:', time)
return schedle
math = name('math')
math('9:00')
# math will take at: 9:00
要点:
- 闭包的特点就是:内部函数调用外部环境的变量
- 该函数作为对象返回,夹带了外部变量
- 可以理解为返回的函数对象,作为变量名,重新赋值(指定动作)