函数进阶

一,命名空间和作用域

1,命名空间的本质:存放名字与值的绑定关系

2,命名空间一共分为三种:

  全局命名空间

  局部命名空间

  内置命名空间

三种命名空间的加载顺序:内置命名空间(程序运行前加载)->全局命名空间(程序运行中:从上到下加载)->局部命名空间(程序运行中:调用时才加载)

三种命名空间取值时的顺序:

  在局部调用:局部命名空间->全局命名空间->内置命名空间

  在全局调用时:全局命名空间.>内置命名空间

3,作用域:

作用域就是作用范围,按照生效范围可以分为全局作用域和局部作用域。

 

全局作用域:包含内置命名空间、全局命名空间,在整个文件的任意位置都能被引用、全局有效

 

局部作用域:局部命名空间,只能在局部范围生效

globals和locals方法

print(globals())
print(locals())
在全局调用
def func():
    a=10
    b=20
    print(globals())
    print(locals())
func()
在局部调用

globl关键字

a=10
def func():
    global a
    a=20
print(a)
func()
print(a)
View Code

 

二,函数的嵌套和作用域链

函数的嵌套调用

 

def max2(x,y):
    m  = x if x>y else y
    return m

def max4(a,b,c,d):
    res1 = max2(a,b)
    res2 = max2(res1,c)
    res3 = max2(res2,d)
    return res3

# max4(23,-7,31,11)

 

函数的嵌套定义

def demo1():
    def demo2():
        print('this is demo2')
    print('this is demo1')
    demo2()
demo1()
def demo1():
    def demo2():
        def demo3():
            print('this is demo3')
        print('this is demo2')
        demo3()
    print('this is demo1')
    demo2()
demo1()

函数的作用域链

a=10
def demo1():
    a=1
    def demo2():
        print(a)
    demo2()
demo1()
def demo1():
    a=2
    def demo2():
        def demo3():
            print(a)
        demo3()
    demo2()

demo1()
def demo1():

    def demo2():
        a=3
    a=2
    print('%s in demo1'%a)
    demo2()
demo1()

 

nonlocal关键字

def f():
    a = 3
    def f1():
        a = 1
        def f2():
            nonlocal a
            # 1.外部必须有这个变量
            # 2.在内部函数声明nonlocal变量之前不能再出现同名变量
            # 3.内部修改这个变量如果想在外部有这个变量的第一层函数中生效

            a = 2
        f2()
        print('a in f1 : ', a)
    f1()
    print('a in f : ',a)

f()

三,函数名的本质

函数名本质上就是函数的内存地址

1,可以被引用

2,可以被当做容器类型的元素

3,可以当做函数的参数和返回值

  也就是说和普通变量一样用

四,闭包函数

 

内部函数包含对外部作用域而非全局作用域名字的引用,该内部函数称为闭包函数

def func():
    name='wxp'
    def inner():
        print(name)
    return inner
func()()

判断闭包函数的方法__closure__

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

f=func()
f()

 

posted @ 2017-07-26 16:36  Moses^  阅读(172)  评论(0编辑  收藏  举报