装饰器
Posted chqworkhome
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了装饰器相关的知识,希望对你有一定的参考价值。
装饰器是一个函数,用于装饰其他函数:
1、不修改原函数调用方式
2、不修改原函数代码
######################################################################
import time
def testNew(func):
def wapper(*arg, **kwargs):
start_time = time.time()
result = func(*arg, **kwargs)
end_time = time.time()
print("Test Func run compelete, using %s seconds" %(end_time - start_time))
return result
return wapper
#@testNew 等同于 test = testNew(test)
@testNew
def studentInfo(name, age, sex):
time.sleep(1)
return ("Student %s, Age %d, Sex: %s" %(name, age, sex))
@testNew
def studentGrade(name, score):
time.sleep(1)
return ("Student %s, Score %d" %(name, score))
print(studentInfo("陈海权", 21, "男"))
print(studentGrade("陈海权", 98))
######################################################################
import time
def testNew(arg):
a = arg
def test(func):
def wapper(*arg, **kwargs):
print(a)
start_time = time.time()
result = func(*arg, **kwargs)
end_time = time.time()
print("Test Func run compelete, using %s seconds" % (end_time - start_time))
return result
return wapper
return test
# @testNew
@testNew("大家好")
def studentInfo(name, age, sex):
time.sleep(1)
return ("Student %s, Age %d, Sex: %s" % (name, age, sex))
@testNew("大家来啊")
def studentGrade(name, score):
time.sleep(1)
return ("Student %s, Score %d" % (name, score))
print(studentInfo("陈海权", 21, "男"))
print(studentGrade("陈海权", 98))
#########################################################################
以上是关于装饰器的主要内容,如果未能解决你的问题,请参考以下文章