#_*_coding:utf-8_*_
#作者:王佃元
#日期:2019/12/22
# 函数作用域
‘‘‘
L:local 函数局部变量:在def内赋值,则是函数的局部变量,只在函数内有效
E:enclosing 嵌套函数外层范围局部变量:若变量嵌套在def中赋值,则对于嵌套函数来说,变量不是本地的
G:global 全局变量:在def之外声明的
B:biuldin 内置变量
‘‘‘
# 局部变量local
# def local_scope():
# a = 10
# print(a)
# print(a)
# 闭包变量enclosing
# def foo():
# print(‘in the foo‘)
#
# def bar():
# print(‘bar‘)
# bar()
# bar()
# def bar():
# print(‘bar‘)
#局部作用域和全局作用域的访问顺序
# x = 0
# def grandpa():
# x = 1
# def dad():
# x = 2
# def sun():
# x = 3
# print(x)
# sun()
# dad()
# grandpa()
# 局部变量的修改对全局变量的影响
# y = 10
#
#
# def test():
# y = 2
# print(y)
#
#
# test()
# print(y)
#
#
# def dad():
# m = 1
#
# def son():
# n = 2
# print(‘m+n=‘, +m+n)
# print(m)
# son()
#
#
# dad()
def counter(start_num=0):
count = [start_num]
def incr():
count[0] += 1
return count[0], id(count) # 第一次执行count[0]为1
# print(type(incr))
return incr
print(counter()) # 执行counter函数,返回incr的引用
print(counter()()) # 执行counter函数,再执行嵌套函数incr
print(counter()()) # 再次执行counter函数,返回的incr地址未变,说明incr()函数一直在内存中
c = counter() # 将返回的函数引用复制给c
print(c()) # 第一次执行c(),count=1
print(c()) # 第二次执行c(),count+1=2
执行结果如下
<function counter.<locals>.incr at 0x00000000023DA9D0>
(1, 5045120)
(1, 37294208)
(1, 37294208)
(2, 37294208)
原文:https://www.cnblogs.com/python-beginner/p/12081640.html