0
点赞
收藏
分享

微信扫一扫

Python_装饰器的使用

Spinach菠菜 2022-02-11 阅读 65
# import time

# def cal_time(fn):
#     print('我是外部函数,我被调用了!!!')
#     print('fn = {}'.format(fn))

#     def inner():
#         start = time.time()
#         fn()
#         end = time.time()
#         print('代码耗时:{}'.format(end - start))

#     return inner

# @cal_time # 第一件事调用cal_time,第二件事把被装饰的函数传递给fn
# def demo():
#     x = 1
#     for i in range(1,1000):
#         x += i
#     print(x)

# @cal_time
# def foo():
#     print('hello')
#     time.sleep(3)
#     print('wold')

# # 第三件事: 当再次调用demo函数时,此时的demo函数已经不再是上面的demo了,是装饰后的函数
# print('装饰后的demo是{}'.format(demo))  # 此时是装饰后的inner函数
# print('装饰后的foo是{}'.format(foo))
# demo()
# foo()

# 装饰器详解

import time

def cal_time(fn):
    print('我是外部函数,我被调用了!!!')
    print('fn = {}'.format(fn))

    def inner(x):
        start = time.time()
        s = fn(x)
        end = time.time()
        print('代码耗时:{}'.format(end - start))
        return s,end - start
    return inner

@cal_time 
def demo(n):
    x = 0
    for i in range(1,n):
        x += i
    return x

@cal_time
def foo():
    print('hello')
    time.sleep(3)
    print('wold')

m = demo(100000)
print(m)

# 装饰器的使用

# 开放封闭原则
def can_play(fn):
    def inner(x,y,*args,**kwargs):
        if args[0] <= 22:
            fn(x,y)
        else:
            print('太晚了,赶紧睡觉')
    return inner

@can_play   
def play_game(name,game):
    print('{}正在玩{}'.format(name,game))

play_game('张三','王者荣耀',18)
play_game('李四','绝地求生',23)
举报

相关推荐

0 条评论