首页
技术
登录
6mi
u
盘
搜
搜 索
技术
Python笔记(30)装饰器之高阶函数
Python笔记(30)装饰器之高阶函数
技术
2026-04-14
5
#!/user/bin/env python
# -*- coding:utf-8 -*-
# author:berlin
# 实现装饰器知识储备:
#1、 函数即“变量”,有时候函数也相当于变量
# 2、高阶函数
# a、把一个函数名当做实参传给另外一个函数(在不修改被装饰函数源代码的情况下为其附加功能)
# b、返回值中包含函数名
# 3、嵌套函数
# 高阶函数+嵌套函数 => 装饰器
# 高阶函数-情况1:(把一个函数名当做实参传给另外一个函数)
# def bar():
# print('in the bar')
#
# def test1(func):
# print(func)
# func()
#
# test1(bar)
# 注:bar()、test1()有括号的都是代表调用。而bar、test1没有括号,代表“门牌号”,显示出来就是
# bar的内存地址。然后func=bar,再通过func()调用以及打印。逻辑大体如下:
# def bar():
# print('in the bar')
#
# def foo():
# print('in the foo')
# bar()
# foo()
# 高阶函数-情况2:(把一个函数名当做实参传给另外一个函数(在不修改被装饰函数源代码的情况下为其附加功能))
# import time
# def bar():
# time.sleep(3)
# print('in the bar')
#
# def test2(func):
# start_time=time.time()
# func() #run bar
# stop_time=time.time()
# print('the func run time is %s' %(stop_time-start_time)) #附加计算功能
# test2(bar)
# 高阶函数-情况3:(返回值中包含函数名(不修改函数的调用方式))
import
time
def
bar
(
)
:
print
(
'in the bar'
)
def
test3
(
func
)
:
print
(
func
)
# 2、打印bar的内存地址,func=bar
func
(
)
# 3、调用bar(),即调用(打印)bar的返回值“in the bar”
return
func
# 4、返回值,func=bar,故也是返回bar的内存地址--------返回值中包含函数名
t
=
test3
(
bar
)
# 1、实参bar赋给形参func
print
(
'打印返回值:'
,
t
)
# 5、打印test3的返回值
转载请注明原文地址:https://ipadbbs.8miu.com/read-64221.html
最新回复
(
0
)