1, 函数名的内存地址,print(func)
2, 函数名可以赋值给其他变量
3, 函数名可以当做容器类的元素
4, 函数名可以当做函数的参数.
5, 函数名可以当做函数的返回值.
学名:第一对象
函数名的内存地址:
def func(): print(555) print(func) # <function func at 0x00000000003E1E18>
结果:
def func1(): print(111) f = func1 f() # func()
def func():
print(555)
def func1():
print(111)
def func2():
print(222)
def func3():
print(444)
l1 = [func(),func1(),func2(),func3()]
for i in l1:
i

def func2(): print(222) def func3(x): x() # func2() func3(func2)

def func2(): print(222) def func3(x): print(a) # func2() return a a = 3 ret = func3(a) print(ret)

ef func2(): print(222) def func3(x): print(a) # func2() return a a = 3 ret = func3(a) print(ret)

二 闭包
内层函数,对外层函数(非全局)的变量的引用,叫做闭包
闭包函数:
内部函数包含对外部作用域而非全剧作用域变量的引用,该内部函数称为闭包函数
函数内部定义的函数称为内部函数由于有了作用域的关系,我们就不能拿到函数内部的变量和函数了。如果我们就是想拿怎么办呢?返回呀!
我们都知道函数内的变量我们要想在函数外部用,可以直接返回这个变量,那么如果我们想在函数外部调用函数内部的函数呢?
是不是直接就把这个函数的名字返回就好了
这才是闭包函数最常用的用法
判断闭包的方法
#输出的__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()
def wrapper(): name = ‘alex‘ def inner(): print(name) inner() print(inner.__closure__) # 检测是不是闭包 cell 就是b包 wrapper()

全局的name="alex"不是闭包:
name = ‘alex‘ def wrapper(): def inner(): print(name) inner() print(inner.__closure__) # 检测是不是闭包 None 就不是b包 wrapper()

闭包:
def wrapper(x): def inner(): print(x) inner() print(inner.__closure__) # cell wrapper(‘alex‘)

def wrapper(x): def inner(): print(666) inner() wrapper(‘Alex‘)

def wrapper(): def inner(): print(666) return inner # wrapper() # inner wrapper()()

闭包的用处:
如果说你内存函数是个闭包,python内部有一个机制,遇到闭包,
他会在内存中开启一个内存空间,不会随着函数的结束而关闭.
爬虫例子:
from urllib.request import urlopen print(urlopen(‘http://www.cnblogs.com/jin-xin/articles/8259929.html‘).read()) def index(url): content = urlopen(url).read() def get(): with open(‘爬虫‘,‘a‘) as f1: f1.write(content.decode(‘utf-8‘)) return get index(‘http://www.cnblogs.com/jin-xin/articles/8259929.html‘)()


def wrapper(): money = 1000 def func(): name = ‘eva‘ def inner(): print(name,money) return inner return func f = wrapper() # func i = f() # inner I()
