当前位置: 移动技术网 > IT编程>脚本编程>Python > day10 python全栈学习笔记

day10 python全栈学习笔记

2018年12月04日  | 移动技术网IT编程  | 我要评论

斗战神灵猴棍势如山,东方花园爱唯侦察,热血无赖天线

函数进阶

函数进阶
1,命名空间和作用域
内置命名空间
python解释器,一启动时就加在在内存中
全局命名空间
从上到下执行的过程中一次加在到内存里
局部命名空间
就是函数内部的空间,再用的时候

2,作用域
全局作用域
局部作用域

local,global 关键字的用法

nonlocal 只会对局部变量有影响,由邻近到最外层,不会影响全局变量

函数本质(函数名就是内存地址)

def func():
    print(123)

func()              #函数名就是内存地址
func2 = func        #函数名可以赋值
func2()


l = [func,func2]    #函数名可以作为容器类型的元素
print(l)

for i in l:
    i()

def func():
    print(123)
def func3(f):
    f()
    return f           #函数名可以作为返回值

laoda = func3(func)    #函数名也可以作为函数的参数
laoda()
函数名的使用

函数嵌套

a = 1
def outer():
    a = 1
    def inner():
        a = 2
        def inner2():
            nonlocal a     #nonlocal 对离它最近的上一层找该变量,一直找到局部变量头部,不会找全局变量。全局变量用global。
            a += 1
            print('inner2 a=%s' %a)
        inner2()
        print('inner a=%s' %a)
    inner()
    print('outer a=%s' %a)

print(a)
outer()
实现代码

闭包 (嵌套函数,内部函数调用外部变量)

# 闭包,嵌套函数,内部函数调用外部函数的变量
#
#
# 我们常用的闭包的形式是这样,闭包的作用和好处是可以延长内部变量的生命周期,在程序结束执行之前不会消失。
def outer():
    a = 1
    def inner():
        print(a)
    return inner

inn = outer()
inn()



#爬虫当中采用的一种闭包形式。
import urllib
from urllib.request import urlopen
# ret = urlopen('http://www.cnblogs.com/eva-j/articles/7156261.html').read()
# print(ret)

def get_url():
    url = 'http://www.cnblogs.com/eva-j/articles/7156261.html'
    def get():
        ret = urlopen(url).read()
        print(ret)
    return get

get_func = get_url()
get_func()
实现代码

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网