python基础之Day12

一、闭包函数

什么是闭包函数?

闭:函数是一个内部函数

包;指的是该函数包含对外部作用域(非全局作用域)名字的引用。

给函数传值的方式有两种:

1、使用参数直接给函数传值

2、包给函数

1
2
3
4
5
6
def  outter(x):
     def  inner():
             print (x)
     return  inner()
f - outter( 10 )
f()

二、装饰器

器:工具,而程序中的函数就具备某一种功能的工具

装饰:指的就是为被装饰对象添加额外的功能,就目前知识来看,定义装饰器就是定义一个函数,只不过该函数的功能是用来为其他函数添加额外功能的

其实:

装饰器本身其实可以是任意可以调用的对象

被装饰的对象也可以是任意可以调用的对象

为什么有装饰器:

因为软件的维护应该遵循开放封闭的原则,开放封闭的原则指的是:

软件一旦上线运行后,对修改源代码是封闭的,对扩展功能是开放的

装饰器的实现必须遵循两大原则:

1、不修改被装饰对象的源代码

2、不修改被装饰对象的调用方式

装饰器就是在遵循1、2的原则下为被装饰对象添加新功能

1
2
3
4
5
6
7
8
9
10
11
12
13
import  time
def  index():
     print ( 'welcome to index' )
     time.sleep( 3 )
def  timmer(func):
     def  wrapper():
         start = time.time()
         func()
         stop = time.time()
         print ( 'run time is %s' % (stop - start))
     return  wrapper
index = timmer(index)
index()

 装饰器语法糖

在被装饰对象上方,并且是单独一行上写上@装饰器名

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import  time
def  timmer(func):
     #func=最原始的index
     def  wrapper( * args, * * kwargs):
         start = time.time()
         res = func( * args, * * kwargs)
         stop = time.time()
         print ( 'run time is %s'  % (stop  -  start))
         return  res
     return  wrapper
 
@timmer  # index=timmer(index)
def  index():
     print ( 'welcome to index' )
     time.sleep( 3 )
     return  123
 
@timmer  # home=timmer(home)
def  home(name):
     print ( 'welcome %s to home page'  % name)
     time.sleep( 2 )
 
res = index()
home( 'egon' )

猜你喜欢

转载自www.cnblogs.com/chicokiko/p/9188707.html