Python装饰器的使用
2021/7/9 17:36:48
本文主要是介绍Python装饰器的使用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
装饰器和装饰器
def func():
print(111)
return 1
print(222)
return 2
print(333)
return 3
运行结果
a=func()
111a
1
def func():
print(111)
yield 1
print(222)
yield 2
print(333)
yield 3
运行结果a=func()
a
<generator object func at 0x0000027D296712A0>next(a)
111
1next(a)
222
2
斐波那契数列
end为次数
def fib(end):
n,a,b=0,0,1
while n<end:
a,b=b,a+b
yield b
n+=1
运行结果
a=fib(5)
a
<generator object fib at 0x0000022972F012A0>next(a)
1next(a)
2next(a)
3next(a)
5next(a)
8next(a)
Traceback (most recent call last):
File "<pyshell#16>", line 1, in
next(a)
StopIteration
装饰器
闭包形势
def func(f):
def func1(x):
x*=10
f()
a=input('请输入:')
print('我是额外增加的函数')
return x
return func1
使用装饰器
@func
def test():
print('我是基础函数')test()
我是基础函数
我是额外增加的函数
@func
def test1():
print('我也是基础函数')test1()
我也是基础函数
我是额外增加的函数test(10)
我是基础函数
我是额外增加的函数
100
这篇关于Python装饰器的使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-09-18初探Python股票自动化交易:入门指南
- 2024-09-18Python量化入门:轻松掌握量化分析基础与实战
- 2024-09-18Python量化交易:入门指南与实践
- 2024-09-18Python量化交易:入门指南与实战技巧
- 2024-09-14Python人工智能项目实战:从零开始的实践指南
- 2024-09-14探索Python人工智能资料:初学者的指南
- 2024-09-14Python人工智能资料:初学者的全面指南
- 2024-09-13Matplotlib入门:轻松绘制Python数据可视化图表
- 2024-09-13Python人工智能:初学者的入门指南
- 2024-09-13Python人工智能:轻松入门与实践