python装饰器

2017-09-02  本文已影响0人  Evtion

最近在学习python3,对于python的装饰器,多线程以及异步IO有点卡顿。这两天在研究python的装饰器,之前在看廖雪峰大神的装饰器感觉一脸懵逼。转而去看伯乐在线的装饰器教程,这里不是做广告。伯乐在线的确解决挺多疑惑。仔细阅读了很多作者的装饰器教程,特此做个总结来加深对python的装饰器的了解。

1.函数
def now(func):
  func()
def hello():
  print("hello world")
now(hello)
#直接输出 hello world
2. 作用域
1. def func():
    name="kiwis"
    print("my name is %s"%name)
   func()
# python shell环境1输出 my name is kiwis
2. 
name ="DB"
def func():
  name="kiwis"
  print("my name is %s"%name)
func()
# python shell环境1输出 my name is kiwis
3. 
name ="DB"
def func():
  print("my name is %s"%name)
func()
# python shell环境1输出 my name is DB
3.装饰器
from datetime import datetime
def logtime(func): 
  def runFun(*args,**kwargs):
    print("the start time is %s"%datetime.now())
    res=func(*args, **kwargs)
    print("the end time is %s"% datetime.now())
    return res
  return runFun()
def add():
  print("hello world")
add=logtime(add())
from datetime import datetime
def logtime(func): 
  def runFun(*args,**kwargs):
    print("the start time is %s"%datetime.now())
    res=func(*args, **kwargs)
    print("the end time is %s"% datetime.now())
    return res
  return runFun()
@logtime
def add():
  print("hello world")
from datetime import datetime
def logtime(func): 
  @functools.wrap(func)
  def runFun(*args,**kwargs):
    print("the start time is %s"%datetime.now())
    res=func(*args, **kwargs)
    print("the end time is %s"% datetime.now())
    return res
  return runFun()
@logtime
def add():
  print("hello world")

python装饰器有针对函数的装饰器和对象的装饰器。下次继续阐述一下面对对象的装饰器。

上一篇 下一篇

猜你喜欢

热点阅读