python 全栈开发,Day6

python之函数进阶

一、引言

现在我有个问题,函数里面的变量,在函数外面能直接引用么?

 

def func1():
    m = 1
    print(m)

print(m)  #这行报的错

执行报错:

NameError: name 'm' is not defined


上面为什么会报错呢?现在我们来分析一下python内部的原理是怎么样:

  我们首先回忆一下Python代码运行的时候遇到函数是怎么做的,从Python解释器开始执行之后,就在内存中开辟里一个空间,每当遇到一个变量的时候,就把变量名和值之间对应的关系记录下来,但是当遇到函数定义的时候,解释器只是象征性的将函数名读如内存,表示知道这个函数存在了,至于函数内部的变量和逻辑,解释器根本不关心。

  等执行到函数调用的时候,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!
View Code

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

命名空间一共分为三种:

  全局命名空间

  局部命名空间

  内置命名空间

*内置命名空间中存放了python解释器为我们提供的名字:input,print,str,list,tuple...它们都是我们熟悉的,拿过来就可以用的方法。

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

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

取值顺序

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

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

综上所述,在找寻变量时,从小范围,一层一层到大范围去找寻。

作用域

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

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

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

globals和locals方法

在全局调用globals和locals
在局部调用locals和globals
global关键字,nonlocal关键字

global:

  1,声明一个全局变量。

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

 

global关键字举例:

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

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

执行输出:

3
2


ps:对可变数据类型(list,dict,set)可以直接引用不用通过global。

对于可变数据类型的应用举例:

li = [1,2,3]
dic = {'a':'b'}

def change():
    li.append('a')
    dic['q'] = 'g'
    print(dic)
    print(li)
change()
print(li)
print(dic)

执行输出:

{'a': 'b', 'q': 'g'}
[1, 2, 3, 'a']
[1, 2, 3, 'a']
{'a': 'b', 'q': 'g'}


nonlocal:

  1,不能修改全局变量。

  2,在局部作用域中,对父级作用域(或者更外层作用域非全局作用域)的变量进行引用和修改,并且引用的哪层,从那层及以下此变量全部发生改变。

 

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()

执行输出:

10
30
30
42

 

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

函数的嵌套调用

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

res = max4(23,-7,31,11)
print(res)

函数的嵌套定义

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()

执行输出:

in f1
in f2
in f1
in f2
in f3


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

作用域链应用举例

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
a in f1 : 1

 

四、函数名的本质

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

1.可以被引用

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

f = func
print(f)

执行输出:

<function func at 0x00000281719B7F28>


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']()

执行输出:

f1
f2


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

def f1():
    print('f1')

def func1(argv):
    argv()
    return argv

f = func1(f1)
f()

执行输出:

f1
f1


第一类对象的概念

第一类对象(first-class object)指
1.可在运行期创建
2.可用作函数参数或返回值
3.可存入变量的实体。


*不明白?那就记住一句话,就当普通变量用

 

五、闭包

def func():
    name = '太白金星'
    def inner():
        print(name)

闭包函数:

内部函数包含对外部作用域而非全剧作用域变量的引用,该内部函数称为闭包函数
#函数内部定义的函数称为内部函数

 

由于有了作用域的关系,我们就不能拿到函数内部的变量和函数了。如果我们就是想拿怎么办呢?返回呀!

我们都知道函数内的变量我们要想在函数外部用,可以直接返回这个变量,那么如果我们想在函数外部调用函数内部的函数呢?

是不是直接就把这个函数的名字返回就好了?

这才是闭包函数最常用的用法

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

f = func()
f()

执行输出:eva

 

判断闭包函数的方法__closure__

#输出的__closure__有cell元素 :是闭包函数
def func():
    name = 'eva'
    def inner():
        print(name)
    print(inner.__closure__)
    return inner

f = func()
f()

#输出的__closure__为None :不是闭包函数
name = 'egon'
def func2():
    def inner():
        print(name)
    print(inner.__closure__)
    return inner

f2 = func2()
f2()

执行输出:

(<cell at 0x000002BDF5900B58: str object at 0x000002BDF5A85B20>,)
eva
None
egon

 

闭包嵌套

def wrapper():
    money = 1000
    def func():
        name = 'eva'
        def inner():
            print(name,money)
        return inner
    return func

f = wrapper()
i = f()
i()

执行输出:

eva 1000


闭包函数获取网络应用

from urllib.request import urlopen

def index():
    url = "http://www.py3study.com"
    def get():
        return urlopen(url).read()
    return get

xiaohua = index()
content = xiaohua()
print(content)

执行输出一堆html代码

 

posted @ 2018-03-17 17:16  肖祥  阅读(539)  评论(2编辑  收藏  举报