社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

Python(十五)装饰器和迭代器

Lonelyroots • 2 年前 • 206 次点击  

今天运气真的好,连中了两张10000加成卡!来好文推荐啦!

简友们觉得自己的文章写的不错!私信发我链接,我来给你助力消零!

'''
定义函数:def 函数名()
调用函数:函数名()
return ①结束函数,②带出(返回)函数的返回值
yield   带出(返回)生成器对象,暂停函数方法,可以进行迭代
函数里面加上yield关键字,则表示该函数是一个生成器,便于分段处理
'''
def fun():
    print(1)
    yield 5
    print(3)
    yield 5
    print(5)

f = fun()       # 返回生成器对象
print(next(f))     # 1 5
next(f)     # 3
print(next(f))      # 迭代完了,会报错StopIteration
'''
斐波那契数列练习:
    斐波那契数列:指的是这样一个数列:0、1、1、2、3、5、8、13、21、34
'''
"""①普通做法"""
def fbnq(n):        # n决定最终次数
    a,b,m=0,1,0     # m统计次数
    while m<n:
        a,b=b,a+b
        m+=1
    print(b)
n = int(input("请输入一个数:"))
fbnq(n)


"""②yield做法"""
def fbnq(n):        # n决定最终次数
    a,b,m=0,1,0     # m统计次数
    while m<n:
        a,b=b,a+b
        yield b
        m+=1
f = fbnq(4)
for i in f:
    print(i)
# print(next(f))
# print(next(f))
# print(next(f))
# print(next(f))
'''
装饰器:回调+闭包
闭包:外层函数返回内层函数的函数体
回调:把一个函数作为参数传递给另一个函数
'''
"""回调"""
def fun():
    print("我是fun函数的执行结果")

def funa(f):    # 必备参数
    f()     # 函数体才可以加括号
    print("我是funa函数的执行结果")

funa(fun)   # 回调,f() = fun()


"""闭包"""
def fun():
    def func():
        print("内层函数执行结果")
    return func

a = fun()
a()


"""
@fun 装饰器:@+闭包函数
    加上装饰器的函数,在调用过程中,实际调用的是闭包函数返回的函数体
"""
def fun(f):
# now:参数f是mao这个函数体
    def func():
        f()     # f是函数体
        print("内层函数执行结果")
    return func

@fun
# now:装饰器作用 fun(mao),把mao这个函数体作为参数传入fun函数中,也就是起了回调作用
def mao():
    print("猫咪只会卖萌")

a = fun(mao)
# now:返回func函数体用变量a接收,a就是func也是mao
print(a)
# outputs:<function fun.<locals>.func at 0x000001FB6C6D1B70>

mao()
# now:mao()也就是func(),底层逻辑是mao=fun(mao)
# outputs:猫咪只会卖萌
#         内层函数执行结果


"""
不改变函数内部结构 给函数加功能:
    这里就可以使用装饰器,给函数加功能
    装饰器:闭包+函数
"""
def funa(fun):
    def funb():
        fun()
        print("Lonelyroots还有才华")
    return funb

@funa       # 装饰器funa(func),将func函数体作为参数传入fun
def func():
    print("Lonelyroots不仅有颜值")

func()
# outputs:Lonelyroots不仅有颜值
#         Lonelyroots还有才华

文章到这里就结束了!希望大家能多多支持Python(系列)!六个月带大家学会Python,私聊我,可以问关于本文章的问题!以后每天都会发布新的文章,喜欢的点点关注!一个陪伴你学习Python的新青年!不管多忙都会更新下去!一起加油!

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/121718
 
206 次点击