# 装饰器
# 特征: 是用一个@开头的字符串
# 装饰器一般用来装饰函数、或者类的方法
# 被装饰后的函数,一般是在原有的函数基础上,会多出增长一点功能
# 通常来讲装饰器自己也是一个函数
#
# def test(name):
# def test_in():
# print(name)
# return test_in
#
# func = test('peiyanan')
# func()app
'''
逻辑思想:①首先把peiyanan实参传递给test函数
②在执行test函数时,又返回到test_in函数
③执行test_in函数并打印输出
'''函数
# =================================================================================
# 不带参数的装饰器(装饰器、被装饰函数都不带参数)
# import time
# def showTime(func):
# def wrapper():
# start = time.time()
# func()
# end = time.time()
# print('spend is {}'.format(end-start))
#
# return wrapper
#
#
#
# @showTime # foo = showTime(foo)
# def foo():
# print('foo..')
# time.sleep(3)
#
#
# foo()orm
'''
逻辑思想:①首先将foo函数当作参数的形式传递到showTime函数中去
②在执行showTime函数的同时,会先打印出foo函数中的
③而后又将返回给wrapper函数
④最后逕wrapper函数并打印输出
'''字符串
# ==================================================================================
# 带参数的被装饰的函数
import time
def showTime(func):
def wrapper(x, y):
start = time.time()
func(x, y)
end = time.time()
print('spend is {}'.format(end-start))form
return wrapperclass
@showTime # foo = showTime(foo)
def foo(x, y):
print(x+y)
time.sleep(3)test
foo(4, 5)import
'''
逻辑思想:①foo函数调用,执行foo函数体并打印输出
②接着showTime函数调用foo(这里foo既能够看作一个参数,也能够看作是一个函数),传递给showTime函数体
③执行showTime函数体,遇到return,又返回给了wrapper函数体
④执行wrapper函数体时,一次执行并最后输出
'''基础
# 使用装饰器的缺点
# 不要在装饰器以外添加逻辑功能
# 不能装饰@staticmethod或者@classmethod已经装饰过的方法
# 装饰器会对原函数的原信息进行更改
# 装饰器
# 特征: 是用一个@开头的字符串
# 装饰器一般用来装饰函数、或者类的方法
# 被装饰后的函数,一般是在原有的函数基础上,会多出增长一点功能
# 通常来讲装饰器自己也是一个函数
#
# def test(name):
# def test_in():
# print(name)
# return test_in
#
# func = test('peiyanan')
# func()方法
'''
逻辑思想:①首先把peiyanan实参传递给test函数
②在执行test函数时,又返回到test_in函数
③执行test_in函数并打印输出
'''
# =================================================================================
# 不带参数的装饰器(装饰器、被装饰函数都不带参数)
# import time
# def showTime(func):
# def wrapper():
# start = time.time()
# func()
# end = time.time()
# print('spend is {}'.format(end-start))
#
# return wrapper
#
#
#
# @showTime # foo = showTime(foo)
# def foo():
# print('foo..')
# time.sleep(3)
#
#
# foo()
'''
逻辑思想:①首先将foo函数当作参数的形式传递到showTime函数中去
②在执行showTime函数的同时,会先打印出foo函数中的
③而后又将返回给wrapper函数
④最后逕wrapper函数并打印输出
'''
# ==================================================================================
# 带参数的被装饰的函数
import time
def showTime(func):
def wrapper(x, y):
start = time.time()
func(x, y)
end = time.time()
print('spend is {}'.format(end-start))
return wrapper
@showTime # foo = showTime(foo)
def foo(x, y):
print(x+y)
time.sleep(3)
foo(4, 5)
'''
逻辑思想:①foo函数调用,执行foo函数体并打印输出
②接着showTime函数调用foo(这里foo既能够看作一个参数,也能够看作是一个函数),传递给showTime函数体
③执行showTime函数体,遇到return,又返回给了wrapper函数体
④执行wrapper函数体时,一次执行并最后输出
'''
# 使用装饰器的缺点# 不要在装饰器以外添加逻辑功能# 不能装饰@staticmethod或者@classmethod已经装饰过的方法# 装饰器会对原函数的原信息进行更改