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)