最新免费视频:www.pythonav.com (冒着被砍死的风险)

装饰器 未完待续。。。

装饰器:

定义:本质是函数,(装饰其他函数)就是为其他函数添加附加功能。

原则:  1.不能修改被装饰的函数的源代码

    2.不能修改被装饰的函数的调用方式

'''

def logger():

  print('logging')

def test1():

  pass

  logger()

def test2():

  logger()

test1()

test2()

'''

 

import time

def timmer(func):

  def warpper(*args,**kwargs):

    start_time=time.time()

    func()

    stop_time=time.time()

    print('the func run time is %s '%(stop_time-start_time))

  return warpper

@timmer

  

def test1():

  time.sleep(3)

  print('in the test1')

 

test()

实现装饰器知识储备:

1.函数即‘变量’

def bar():

  print('in the bar')

def foo():

  print('in the foo')

  bar()

foo()

 

 

def foo():

  print('in the foo')

  bar()

def bar():

  print('in the bar')

foo()

#  第一步 定义  第二步 调用

2.高阶函数

  a:把一个函数名当做实参,传给另外一个函数(在不修改被装饰函数源代码的情况下为其添加功能)

  b:返回值中包含函数名

 

a:

import time

def bar():

  time.sleep(3)

  print('in the bar')

 

def test1(func):

  start_time=time.time()        

  func()   #run bar

  stop_time=time.time()

  print('the func run time is %s'%(stop_time-start_time))

test1(bar)

func=bar

func()

  b:返回值中包含函数名  (函数是变量)(不修改函数的调用方式)

import time

def bar():

  time.sleep(3)

  print('in the bar')

def test2(func):

  print(func)

  return func

#print(test2(bar))

 

t=test2(bar)#是把bar的内存地址传给变量

bar=test2(bar)

#print(t)

t()

bar()# run bar

#如果是test2(bar())  这个是把bar的返回值传给变量 不符合高阶函数的定义

 

3.嵌套函数

def foo():

  def bar():

    print('in the bar')

  bar()

foo()

 

'''def test1():

  test2()

test1()'''      这个是函数的调用      

 

高阶函数+嵌套函数=>装饰器

 

补充:

局部作用域和全局作用域的访问顺序

x=0#全局变量

def grandpa()

  #x=1

  def dad():

    x=2 

    def son():

      x=3

      print x

    son()

  dad()

grandpa()

 

打印结果为3

就近找值 ,从里往外找。

 

 

import time

def timer(func)         # timer(test1)   func=test1

  def deco():

    start_time=time.time()

    func()

    stop_time=time.time()

    print('the func run time is %s'%(stop_time - start_time))

  return deco

#def timer():

#  def deco():

#    pass

 

def test1():

  time.sleep(3)

  print('in the test1')

 

def test2();

  time.sleep(3)

  print('in the test2')

 

test1=timer(test1)

test1()  #====>deco()

#test1=deco(test1)

#deco(test2)

 

这块老师讲的 我没理解了  这个代码也是贴的是进行中代码   最终代码:

import time
def timer(func): #timer(test1) func=test1
def deco(*args,**kwargs):
start_time=time.time()
func(*args,**kwargs) #run test1()
stop_time = time.time()
print("the func run time is %s" %(stop_time-start_time))
return deco
@timer #test1=timer(test1)
def test1():
time.sleep(1)
print('in the test1')

@timer # test2 = timer(test2) = deco test2(name) =deco(name)
def test2(name,age):
print("test2:",name,age)

test1()
test2("alex",22)


待理解再继续写。。。。
posted @ 2017-07-27 19:29  uuuuuuu  阅读(130)  评论(0编辑  收藏  举报

最新免费视频:www.pythonav.com (冒着被砍死的风险)