Python-函数对象及闭包函数
什么是函数对象:
-
在运行时创建
-
能赋值给变量或数据结构中的元素
-
能作为参数传递给函数
-
能作为函数的返回结果
-
1.函数身为一个对象,拥有对象模型的三个通用属性:id、类型、和值。
#!/usr/bin/env python # -*- coding:utf-8 -*- def foo(): print('from foo') foo() print(id(foo)) print(type(foo)) print(foo)
输出
from foo 4406808360 <class 'function'> <function foo at 0x106aa8f28>
2.函数可以被引用,即函数可以赋值给一个变量
还可以把该函数赋值给更多的变量,唯一变化的是该函数对象的引用计数不断地增加,本质上这些变量最终指向的都是同一个函数对象。
#!/usr/bin/env python # -*- coding:utf-8 -*- def foo(): print('from foo') foo() func=foo #引用,赋值 print(foo) print(func) func()
输出
from foo <function foo at 0x10eed8f28> <function foo at 0x10eed8f28> from foo
3.函数可以当做参数传递
def foo(): print('from foo') def bar(func): print(func) func() bar(foo)
输出
<function foo at 0x1047eff28> from foo
4.函数可以作返回值
函数接受一个或多个函数作为输入或者函数输出(返回)的值是函数时,我们称这样的函数为高阶函数
def foo(): print('from foo') def bar(func): return func f=bar(foo) print(f) f()
输出
<function foo at 0x107f29f28> from foo
5.函数可以当作容器类型的元素
容器对象(list、dict、set等)中可以存放任何对象,包括整数、字符串,函数也可以作存放到容器对象中
def foo(): print('from foo') dic={'func':foo} foo() print(dic['func']) dic['func']()
输出
from foo <function foo at 0x10997ef28> from foo
6.函数还可以嵌套
函数嵌套的定义
def f1(): def f2(): print('from f2') def f3(): print('from f3') f3() f2() f1()
输出
from f2 from f3
应用
def get(text): def clean(t): #2 return t[1:] new_text = clean(text) #1 return len(new_text) print(get('python'))
输出
5
- 闭包函数
-
# 一:大前提:
# 闭包函数=名称空间与作用域+函数嵌套+函数对象
# 核心点:名字的查找关系是以函数定义阶段为准
# 二:什么是闭包函数
# "闭"函数指的该函数是内嵌函数
# "包"函数指的该函数包含对外层函数作用域名字的引用(不是对全局作用域)
# 闭包函数:名称空间与作用域的应用+函数嵌套
# def f1():
# x = 33333333333333333333
# def f2():
# print(x)
# f2()
#
#
# x=11111
# def bar():
# x=444444
# f1()
#
# def foo():
# x=2222
# bar()
#
# foo()
# 闭包函数:函数对象
# def f1():
# x = 33333333333333333333
# def f2():
# print('函数f2:',x)
# return f2
#
# f=f1()
# # print(f)
#
# # x=4444
# # f()
# def foo():
# x=5555
# f()
#
# foo()
# 三:为何要有闭包函数=》闭包函数的应用
# 两种为函数体传参的方式
# 方式一:直接把函数体需要的参数定义成形参
# def f2(x):
# print(x)
#
# f2(1)
# f2(2)
# f2(3)
# 方式二:
# def f1(x): # x=3
# x=3
# def f2():
# print(x)
# return f2
#
# x=f1(3)
# print(x)
#
# x()
import requests
# 传参的方案一:
# def get(url):
# response=requests.get(url)
# print(len(response.text))
#
# get('https://www.baidu.com')
# get('https://www.cnblogs.com/linhaifeng')
# get('https://zhuanlan.zhihu.com/p/109056932')
# 传参的方案二:
def outter(url):
# url='https://www.baidu.com'
def get():
response=requests.get(url)
print(len(response.text))
return get
baidu=outter('https://www.baidu.com')
baidu()
cnblogs=outter('https://www.cnblogs.com/linhaifeng')
cnblogs()
zhihu=outter('https://zhuanlan.zhihu.com/p/109056932')
zhihu()