装饰器

#coding:utf-8
from datetime import date,datetime
import functools,time

def hello(func):
    def swapper():
        print "hello"
        return func()
    return swapper

@hello
def printname():
    def printage():
        print '16'
    print "liaoxingrui"
    return printage()

printname()

def log(text):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args,**kw):
            print("call:%s(),%s"%(func.__name__,text))
            return func(*args,**kw)
        return wrapper
    return decorator

@log('cl')
def now():
    print(date.today())


now()
print(now.__name__)


#请设计一个decorator,它可作用于任何函数上,并打印该函数的执行时间:
print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
def printdtime(func):
    def wrapper(*args,**kwargs):
        print("%s execute time is %s"%(func.__name__,datetime.now()))
        return func(*args,**kwargs)
    return wrapper

@printdtime
def says(name):
    print('%s you are very sweet!'%(name))

says('Rey')


def metric(fn):
    def wrapper(*args,**kwargs):
        print('%s executed in %s ms' % (fn.__name__, 10.24))
        return fn(*args,**kwargs)
    return wrapper
@metric
def fast(x, y):
    time.sleep(0.0012)
    return x + y

# print(fast(11, 22))
def makeitalic(func):
    @functools.wraps(func)
    def wrapped():
        # return "<i>"+func()+"</i>"
        print("<i>" + func() + "</i>")
    return wrapped

@makeitalic
def hello():
    return "hello world"
#hello()等同于makeitalic(hello)

print(hello())
print(hello.__name__)
#coding:utf-8
from datetime import date,datetime
import functools,time

def hello(func):
def swapper():
print "hello"
return func()
return swapper

@hello
def printname():
def printage():
print '16'
print "liaoxingrui"
return printage()

printname()

def log(text):
def decorator(func):
@functools.wraps(func)
def wrapper(*args,**kw):
print("call:%s(),%s"%(func.__name__,text))
return func(*args,**kw)
return wrapper
return decorator

@log('cl')
def now():
print(date.today())


now()
print(now.__name__)


#请设计一个decorator,它可作用于任何函数上,并打印该函数的执行时间:
print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
def printdtime(func):
def wrapper(*args,**kwargs):
print("%s execute time is %s"%(func.__name__,datetime.now()))
return func(*args,**kwargs)
return wrapper

@printdtime
def says(name):
print('%s you are very sweet!'%(name))

says('Rey')


def metric(fn):
def wrapper(*args,**kwargs):
print('%s executed in %s ms' % (fn.__name__, 10.24))
return fn(*args,**kwargs)
return wrapper
@metric
def fast(x, y):
time.sleep(0.0012)
return x + y

# print(fast(11, 22))
def makeitalic(func):
@functools.wraps(func)
def wrapped():
# return "<i>"+func()+"</i>"
print("<i>" + func() + "</i>")
return wrapped

@makeitalic
def hello():
return "hello world"
#hello()等同于makeitalic(hello)

print(hello())
print(hello.__name__)


原文地址:https://www.cnblogs.com/pipile/p/12604916.html