装饰器

 

定义一个函数:

def outer():
  def inner():
    print("this is first func")
    print("this is end func")
  return inner

t=outer()
print(t)
t()

 """

<function outer.<locals>.inner at 0x00000000006D01E0>
this is first func
this is end func

"""

 

 

在不改变原来函数的情况下 怎么样在

print("this is first func")
print("this is end func")

 之间加一个功能呢!!

 

 

def outer(fun):
  def inner():
    print("this is first func")
    fun()
    print("this is end func")
  return inner

def fun():
  print("this is a new func")

fun=outer(fun)

print(fun)
print(fun())

"""

<function outer.<locals>.inner at 0x0000000000B90268>
this is first func
this is a new func
this is end func
None

"""

 

使用装饰器:

def outer(fun):
  def inner():
    print("this is first func")
    fun()
print("this is end func")
return inner

@outer    # ===>  fun=outer(fun)
def fun():
  print("this is a new func")

fun()

"""

this is first func
this is a new func
this is end func

"""

 

posted @ 2017-11-03 23:27  xuanhui  阅读(137)  评论(0编辑  收藏  举报