Python3.0之后加入新特性Decorators,以@为标记修饰function和class。有点类似c++的宏和java的注解。Decorators用以修饰约束function和class,分为带参数和不带参数,影响原有输出,例如类静态函数我们要表达的时候需要函数前面加上修饰@staticmethod或@classmethod,
In [1]:
def spamrun(fn):
def sayspam(*args):
print("spam,spam,spam")
fn(*args)
return sayspam
@spamrun
def useful(a, b):
print(a * b)
if __name__ == "__main__":
useful(2, 5)
In [4]:
"""
if __name__ == "__main__":
useful = spamrun(useful)
useful(a, b)
"""
Out[4]:
In [ ]:
def spamrun(fn):
def sayspam(*args):
print("spam,spam,spam")
fn(*args)
return sayspam
def spamrun1(fn):
def sayspam1(*args):
print("spam1,spam1,spam1")
fn(*args)
return sayspam1
@spamrun
@spamrun
@spamrun1
def useful(a, b):
print(a * b)
if __name__ == "__main__":
useful(2, 5)
In [8]:
def attrs(**kwds):
def decorate(f):
for k in kwds:
setattr(f, k, kwds[k])
return f
return decorate
@attrs(versionadded="2.2", author="Guido van Rossum")
def mymethod(f):
print(getattr(mymethod, 'versionadded', 0))
print(getattr(mymethod, 'author', 0))
print(f)
if __name__ == "__main__":
mymethod(2)
In [13]:
import time
def timer(func):
def wrapper(*args, **kw):
begin_time = time.time()
func(*args, **kw)
end_time = time.time()
print(f'{func.__name__} cost time:{end_time-begin_time}s')
return wrapper
@timer
def test():
time.sleep(1)
print('test_1111')
if __name__ == '__main__':
test()