Python基础九函数进阶(一)

Q:Python运行代码时,遇到函数是怎么做到的?

A:从Python解释器开始执行之后,就在内存中开辟一个空间,每当遇到一个变量的时候,就把变量名和值之间的对应关系记录下来,但是当遇到函数定义的时候,解释器只是象征性的将函数名读入内存,表示知道这个函数存在了,至于函数内部的变量跟逻辑,解释器根本不关心。

  当执行到函数调用的时候,Python解释器会再开辟一块内存来存储这个函数里面的内容,这个时候,才关注函数里面有哪些变量,而函数中的变量会存储在新开辟出来的内存中,函数中的变量只能在函数内部使用,并且会锁着函数执行完毕,这块内存中的所有内容也会被清空。

这个“存放名字与值得空间”被我们叫做——命名空间

代码在运行开始,创建的存储”变量名与值得关系“的空间叫做全局命名空间;在函数的运行中开辟的临时空间叫做局部命名空间

一、聊一聊命名空间和作用域

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

python之禅

python之禅
Python之禅

在python之禅中说:命名空间是一种绝妙的理念,让我们尽情的使用发挥吧!

命名空间一共分三种:

  全局命名空间

  局部命名空间

  内置命名空间

内置命名空间中存放了Python解释器为我们提供的名字:

input,print,str,list,tuple等他们都是我们可以直接及使用的方法。

三种命名空间之间的加载与取值顺序:

加载顺序:

    内部命名空间 --> 全局命名空间 --> 局部命名空间

取值顺序

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

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

总而言之,言而总之,程序在寻找变量的时候,是从内向外,从小到大,一层层的去寻找的。

作用域

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

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

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

globals()和locals()方法

print(locals())
print(globals())
def func():
    a = 12
    b = 20
    print(locals())
    print(globals())

func()

在局部调用locals和globals

globals可以查看当前作用域的变量

locals可以查看全局作用与的变量

global关键字,nonlocal关键字。

global:

  1声明一个全局变量。

  2在局部作用域想要对全局作用域的全局变量进行修改时,需要用到global(限于字符串,数字)

def func():
    global a
    a = 3
func()
print(a)


count = 1
def search():
    global count
    count = 2
search()
print(count)

global关键字举例

but:对于可变数据类型(list,dict,set)可以直接饮用不用通过global。(至于为什么我想应该是Python函数引用变量的方式是‘传值’而非‘引用’。具体待后续求证后更新。

nonlocal:

  声明非全局作用域的各个父级作用域,在局部作用域中,对父级作用域(或者更外层作用域非全局作用域)的变量记性引用和修改,并且引用的哪层,从那层及以下此变量全部发上改变。

def add_b():
    b = 42
    def do_global():
        b = 10
        print(b)
        def dd_nonlocal():
            nonlocal b
            b = b + 20
            print(b)
        dd_nonlocal()
        print(b)
    do_global()
    print(b)
add_b()

nonlocal关键字举例

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

  函数的嵌套调用

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 f1():
    print("in f1")
    def f2():
        print("in f2")

    f2()
f1()
###########
def f1():
    def f2():
        def f3():
            print("in f3")
        print("in f2")
        f3()
    print("in f1")
    f2()
    
f1()

函数的嵌套定义

函数的作用域链:小范围作用域可以使用大范围的变量,但是反之不行,他是单向的。

def f1():
    a = 1
    def f2():
        def f3():
            print(a)
        f3()
    f2()

f1()
################
def f1():
    a = 1
    def f2():
        a = 2
    f2()
    print('a in f1 : ',a)

f1()

作用域链应用举例

三、函数名的本质

透过现象看本质,函数名本质上就是内存地址

1可以被引用

def func():
    print('in func')

f = func
print(f)

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

def f1():
    print('f1')


def f2():
    print('f2')


def f3():
    print('f3')

l = [f1,f2,f3]
d = {'f1':f1,'f2':f2,'f3':f3}
#调用
l[0]()
d['f2']()

可以当做容器类型的元素

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

def f1():
    print('f1')

def func1(argv):
    argv()
    return argv

f = func1(f1)
f()

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

猜你喜欢

转载自www.cnblogs.com/gzying-01/p/10206299.html