Python函数的作用域、闭包函数

全局作用域:全局命名空间与内置命名空间的名字都属于全局范围,在整个文件的任意位置都能被引用,全局有效
局部作用域:局部命名空间,只能在局部范围内生效

如果全局有,用全局的。如果全局没有,用内置的。

globals方法:查看全局作用域的名字【print(globals())】
locals方法:查看局部作用域的名字【print(locals())】


global关键字:强制转换为全局变量
注意:这个方法尽量能少用就少用
x=1
def foo():
    global  x  #强制转换x为全局变量
    x=10000000000
    print(x)
foo()
print(x)


nonlocal让内部函数中的变量在上一层函数中生效,外部必须有
x=1
def f1():
    x=2
    def f2():
        # x=3
        def f3():
            # global x#修改全局的
            nonlocal x#修改局部的(当用nonlocal时,修改x=3为x=100000000,当x=3不存在时,修改x=2为100000000 )
                   # 必须在函数内部
            x=10000000000
        f3()
        print('f2内的打印',x)
    f2()
    print('f1内的打印', x)
f1()
print(x)


函数名的本质:就是函数的内存地址,指向了函数的内存地址
def func():
  print('func')
print(func)


函数可以当作数据传递
def foo():
    print('foo')

def bar():
    print('bar')

dic={
    'foo':foo,
    'bar':bar,
}
while True:
    choice=input('>>: ').strip()
    if choice in dic:
        dic[choice]()


函数名可以用做函数的参数
def func():
    print('func')

def func2(f):
    f()
    print('func2')
func2(func)


函数名可以作为函数的返回值
return说明1
def func():
    def func2():
        print('func2')
    return func2
f2=func()
f2()

2.
def f1(x):
    print(x)
    return '123'

def f2():
    ret = f1('s')  #f2调用f1函数
    print(ret)
f2()

3.
def func():
    def func2():
        return 'a'
    return func2   #函数名作为返回值
func2=func()
print(func2())



闭包函数
1.闭 :内部的函数 
2.包 :包含了对外部函数作用域中变量的引用 
def foo(): 
  x=20 
  def inner(): 
    x=10 #如果x定义了,他就用自己的了,就实现不了闭包 
print(x) 


闭包的常用形式: 
def foo(): 
  x=20 
  def inner(): 
    '''闭包函数''' 
    print(x) 
return inner()


判断闭包函数的方法:__closure__
输出的__closure__有cell元素 :是闭包函数
输出的__closure__为None :不是闭包函数

def func():
    name = 'eva'
    def inner():
        print(name)
    print(inner.__closure__)
    return inner

f = func()
f()


闭包的应用案例
from urllib.request import urlopen

def index(url):
    def get():
        return urlopen(url).read()
    return get

baidu=index('http://www.baidu.com')
print(baidu().decode('utf-8'))
原文地址:https://www.cnblogs.com/l10n/p/13914016.html