Python学习笔记(12)装饰器

import time

def show_time(f):

def inner(a, b):
start = time.time()
f(a, b)
end = time.time()
print('spend %s' % (end - start))

return inner


@show_time # add = show_time(add)
def add(a, b):
print(a + b)
time.sleep(1)


add(3, 4)

import time
import functools


def log(func):
@functools.wraps(func)
def wapper():
print('%s' % func.__name__)
func()
return wapper


@log
def now():
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))

2018-04-27 21:56:56
now

functools.wraps 相当于写 wapper.__name__ = now.__name__

不然结果会成为

import time
import functools


def log(func):
# @functools.wraps(func)
def wapper():
print('%s' % func.__name__)
func()
return wapper


@log
def now():
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))


now()
print(now.__name__)

2018-04-27 21:58:32
wapper

装饰器传递参数 如下例

import functools
import time

def log(text):
  def decorator(func):
  functools.wraps(func)
    def wrapper():
      print('%s-%s' % (text, func.__name__))
        func()
    return wrapper
    return decorator

@log('whn')      #now = log('xxx')(now)
def now():
  print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))

now()
 

whn-now
2018-04-27 22:07:48

猜你喜欢

转载自www.cnblogs.com/thyh/p/8964837.html
今日推荐