python - 函数装饰器

1.装饰器的含义

原理:利用函数传参和函数闭包的特性

特点:可以更方便后期的代码修改

语法:@装饰器名 

# 1.使用装饰器
def time_master(func):
    def call_func():
        print("开始调用程序...")
        start = time.time()
        func()
        stop = time.time()
        print("调用程序完成...")
        print(f"调用程序花费的时间:{stop - start:.2f} 秒")
    return call_func

@time_master
# ==> myfunc = time_master(myfunc)
def myfunc():
    time.sleep(2)
    print("hello")
@time_master
def testfunc():
    time.sleep(3)
    print("python")
myfunc()
testfunc()
2.多个装饰器用在同一个函数上的顺序 (从下至上)
def add(func):
    def inner():
        x = func()
        return x + 1
    return inner
def cube(func):
    def inner():
        x = func()
        return x * x * x
    return inner
def square(func):
    def inner():
        x = func()
        return x * x
    return inner
@add
@cube
@square

# add(cube(square(test)))
def test():
    return int(input("请输入一个数:"))
print(test())
import time
3.装饰器中传参
import time
# 3.装饰器中传递参数
def logger(msg):
    def time_master(func):
        def call_func():
           start = time.time()
           func()
           stop = time.time()
           print(f"{msg}调用程序所花费的时间:{(stop - start):.2f}秒")
        return call_func
    return time_master

@logger(msg="A")
def funcA():
    time.sleep(2)
    print("hello")
funcA()

@logger(msg="B")
def funcB():
    time.sleep(5)
    print("PYTHON")
funcB()
4.斐波那契数列
import time
# 斐波那契数列 函数
# 需要几位数的斐波那契数列
def delay(func):
    def call_func():
        time.sleep(1)
        func()
    return call_func
def fib( ):
    back1,back2 = 0,1
    @delay
    def get_fib():
        nonlocal back1,back2
        back1,back2 = back2,back1 + back2
        print(back1 ,end="")
    return get_fib

def my_func(n):
    f = fib()
    for i in range(n):
        f()
n = int(input("请输入需要几位数的斐波那契数列:"))
my_func(n)
5.判断字符串或者数字类型
def test_type(correct_type):
    def outter(func):
        def inner(arg):
            if(type(arg) == correct_type):
                return func(arg)
            else:
                print("参数类型不对")
        return inner
    return outter
print("-------判断整数类型-----")
@test_type(int)
def funA(x):
     print(x * x)
funA(4)
print("-------判断字符串类型-----")
@test_type(str)
def funB(x):
    print(f"字符串是:{x}")
funB(4)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值