Python装饰器的使用

2021/7/9 17:36:48

本文主要是介绍Python装饰器的使用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

装饰器和装饰器
def func():
print(111)
return 1
print(222)
return 2
print(333)
return 3
运行结果

a=func()
111

a
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
1

next(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)
1

next(a)
2

next(a)
3

next(a)
5

next(a)
8

next(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装饰器的使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程