python-装饰器-1

装饰器的定义:

本质上是一个函数,用来装饰其他函数,即:为其他函数提供附加功能的函数

遵循的原则:

1、不修改被装饰函数的源代码

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

需要掌握的知识点:

1、函数即“变量”

2、高阶函数:

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

      b. 返回值中包含函数名(在不修改被装饰函数的调用方式的情况下调用函数)

3、嵌套函数:

      在一个函数体内,用def去重新声明一个函数

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

高阶函数举例:
a.把一个函数名当做实参传给另外一个函数

import time

#高阶函数
def bar():
	time.sleep(3)
	print('in the bar')

def test1(func):
	start_time = time.time()
	func()
	stop_time = time.time()
	print('the func run time is %s' % (stop_time-start_time))

test1(bar)

 执行结果:

in the bar
the func run time is 3.010805130004883

 b.返回值中包含函数名

import time
#高阶函数
def test2(func):
	print(func)
	return func

def bar():
	time.sleep(3)
	print ('in the bar')

bar = test2(bar)
bar()

 执行结果:

<function bar at 0x005DE1E0>
in the bar

 嵌套函数举例:

#嵌套函数
def foo():
	print ('in th foo')
def bar():
	#time.sleep(3)
	print ('in the bar')
	bar()

foo()

 执行结果:

in th foo
in the bar

 注:嵌套函数的变量作用域

x = 0
def grandpa():
	x=1
	def dad():
		x=2
		def son():
			x=3
			print (x)
		son()
	dad()

grandpa()

 执行结果:

3

 结论:嵌套函数的变量作用域:由内而外

普通装饰器:

def timer(func):    #timer(test1) func = test1
    def deco():
        start_time = time.time()
        func()  #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(3)
    print('in the test1')


test1()

执行结果:

in the test1
the func run time is 3.0113539695739746

中级装饰器:

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
def test2(name,age,time):     #中级装饰器
    print (name,age,time)
    print ('in the test2')

test2('test2',22,time.time())

 执行结果:

test2 22 1484531528.9299865
in the test2
the func run time is 0.0

猜你喜欢

转载自funny121.iteye.com/blog/2353240