码迷,mamicode.com
首页 > 编程语言 > 详细

Python学习笔记(12)装饰器

时间:2018-04-27 23:04:02      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:wrap   port   decorator   alt   func   装饰器   传递   参数   div   

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

Python学习笔记(12)装饰器

标签:wrap   port   decorator   alt   func   装饰器   传递   参数   div   

原文地址:https://www.cnblogs.com/thyh/p/8964837.html

(0)
(0)
   
举报
评论 一句话评论(0
0条  
登录后才能评论!
© 2014 mamicode.com 版权所有 京ICP备13008772号-2
迷上了代码!