当前位置:网站首页>Closures and decorators
Closures and decorators
2022-07-29 01:13:00 【:D...】
Closure
Inner and outer functions are nested , The inner function refers to Not Global variables , The external function returns the object of the internal function
advantage : Renew the life of variables shortcoming : Waste of memory
# Inner and outer functions are nested
def outer(a, b):
def inner():
# Internal functions refer to non global variables under the scope of external functions
print(a + b)
# The outer function returns the inner function object
return inner
outer(5, 9)()
def f1(n):
def f2():
list1 = [i for i in range(1, n+1)]
print(list1)
return f2
f1(9)()
Decorator
Without changing the original function , Additional function extensions to existing functions .
Do not modify the existing functionSource code
andCall mode
Addnew function
The difference between closures and decorators : The decorator is essentially a closure function , But when the decorator has only one parameter and is a function type , He's the decorator , Otherwise, it is closure
# Use the idea of closure to realize Calculate the program usage time print(" It's a fine day today ")
import time
def outer(f):
def inner():
start = time.time()
f()
end = time.time()
print(end - start-1)
return inner
@outer # call Decorator outer
def func(): # func Parameters passed into the decorator f
print(" It's a fine day today ")
time.sleep(1)
func() # Equate to innr()
Universal decorator
# The inner function is consistent with the decorated function { Parameters are consistent , Return consistent }
# Define a decorator , Add to the program print(" Trying to perform addition ") Program function Realize the addition of several numbers by passing parameters
def outer(f):
def inner(*args):
print(" Trying to perform addition ")
f(*args)
return inner
@outer
def f1(*args):
print(sum(args))
f1(5, 9, 9, 45, 34)
# Define a decorator Add <p> </p>
def outer(f):
def inner():
return "<p>" + f() + "</p>"
return inner
@outer
def func():
return " Life is too short , I use python"
print(func())
Multi layer decorator
# The decorator on the first floor decorates The second layer is decorated with ornaments
# The first ornament
def outer(f):
def inner():
print(" This is a decorator 1 Start of execution ")
f()
print(" This is a decorator 1 End of execution ")
return inner
# The second ornament
def outer2(f):
def inner2():
print(" This is a decorator 2 Start of execution ")
f()
print(" This is a decorator 2 End of execution ")
return inner2
@outer
@outer2
def func():
print(" Life is too short , I use python")
func()
Execution results ============>
This is a decorator 1 Start of execution
This is a decorator 2 Start of execution
Life is too short , I use python
This is a decorator 2 End of execution
This is a decorator 1 End of execution
边栏推荐
- Self-attention neural architecture search for semantic image segmentation
- Consumer unit
- [target detection] Introduction to yolor theory + practical test visdrone data set
- Necessary interview skills for Android (including interview questions and learning materials)
- 状态压缩dp-蒙德里安的梦想
- TextKit 自定义UILabel识别链接
- (update 20211130) about the download and installation of Jupiter notebook and its own configuration and theme
- How to smoothly go online after MySQL table splitting?
- 18 diagrams, intuitive understanding of neural networks, manifolds and topologies
- 【idea】查询字段使用位置
猜你喜欢
Necessary interview skills for Android (including interview questions and learning materials)
括号匹配的检验
如何执行建设项目的时间影响分析?
Daniel guild Games: summary and future outlook of this year
递归与分治
对接支付宝支付
In the second round, 1000 okaleido tiger were sold out in one hour after logging in to binance NFT again
电子招标初学者指南
Wechat campus bathroom reservation applet graduation design finished product (5) assignment
ThinkPHP high imitation blue cloud disk system program
随机推荐
ACM SIGIR 2022 | interpretation of selected papers of meituan technical team
(perfect solution) why is the effect of using train mode on the train/val/test dataset good, but it is all very poor in Eval mode
图扑软件亮相 2022 福州数博会,携手共创数字新时代
Linux Redis 源码安装
写作作业一
【ManageEngine】局域网监控软件是什么,有什么作用
新一代超安全蜂窝电池,思皓爱跑上市,13.99万起售
A new generation of ultra safe cellular battery, Sihao aipao, is on the market, starting from 139900
B-tree~
Visual full link log tracking
mysql分表之后怎么平滑上线?
【刷题笔记】二进制链表转整数
Wechat campus bathroom reservation for the finished product of applet graduation design (7) mid term inspection report
mysql存储过程 实现创建一张表(复制原表的结构新建的表)
QT static compiler (MinGW compilation)
“index [hotel/jXLK5MTYTU-jO9WzJNob4w] already exists“
LeTax记录\documentclass{},authoryear属性使用
Time series prediction | MATLAB realizes time series prediction of TCN time convolution neural network
PLATO上线LAAS协议Elephant Swap,用户可借此获得溢价收益
Cookies and sessions