Python高级编程--闭包与装饰器

 装饰器功能,就是在运行原来功能基础上,加上一些其它功能,比如权限的验证,比如日志的记录等等。不修改原来的代码,进行功能的扩展。有了装饰器,就可以提取大量函数中与本身功能无关的类似代码,从而达到代码重用的目的。
装饰器(decorator)功能如下:
  1.引入日志
  2.函数执行时间统计
  3.执行函数前预备处理
  4.执行函数后清理功能
  5.权限校验等场景
  6.缓存

1. 闭包

1.1 函数引用

示例1:

def test1():
    print("--- in test1 func----")

#调用函数
test1()

#引用函数
ret = test1

print(id(ret))
print(id(test1))

#通过引用调用函数
ret()

运行结果:

--- in test1 func----
18477128
18477128
--- in test1 func----

1.2 什么是闭包

定义:
这里写图片描述
在函数内部再定义一个函数,并且这个函数用到了外边函数的变量,那么将这个函数以及用到的一些变量称之为闭包。

示例2:

#定义一个函数
def test(number):

    #在函数内部再定义一个函数,并且这个函数用到了外边函数的变量,那么将这个函数以及用到的一些变量称之为闭包
    def test_in(number_in):
        print("in test_in 函数, number_in is %d"%number_in)
        return number+number_in
    #其实这里返回的就是闭包的结果
    return test_in


#给test函数赋值,这个20就是给参数number
ret = test(20)

#注意这里的100其实给参数number_in
print(ret(100))

#注意这里的200其实给参数number_in
print(ret(200))

运行结果:

in test_in 函数, number_in is 100
120
in test_in 函数, number_in is 200
220

示例3:

def line_conf(a, b):
    def line(x):
        return a*x + b
    return line

line1 = line_conf(1, 1)
line2 = line_conf(4, 5)
print(line1(5))
print(line2(5))

运行结果:

6
25

说明:
这个例子中,函数line与变量a,b构成闭包。在创建闭包的时候,我们通过line_conf的参数a,b说明了这两个变量的取值,这样,我们就确定了函数的最终形式(y = x + 1和y = 4x + 5)。我们只需要变换参数a,b,就可以获得不同的直线表达函数。由此,我们可以看到,闭包也具有提高代码可复用性的作用。
如果没有闭包,我们需要每次创建直线函数的时候同时说明a,b,x。这样,我们就需要更多的参数传递,也减少了代码的可移植性。

2. 装饰器的理解

示例1:

def haha(func):
    print('haha...')
    func()

def hehe():
    print('hehe...')

haha(hehe)

运行结果:

haha...
hehe...

在示例1中:
 haha(hehe)调用了haha(func)方法,把参数hehe传给了func,向下运行打印haha...,再执行func(),因为在之前func变为了hehe,所以执行func()也就是执行hehe().

示例2:

def check_login():
    # 验证1
    # 验证2
    # 验证3
    pass

def f1():
    check_login()
    print('f1')
def f2():
    check_login()
    print('f2')
def f3():   
    check_login()
    print('f3')
def f4():
    check_login()
    print('f4')

在示例2中:
 check_login()定义了验证的方法,f1,f2,f3,f4分别调用以验证,但是这样是不妥的.
 写代码要遵循‘开放封闭原则’,虽然在这个原则是用于面向对象开发,但是也适用于函数式编程,简单来说,它规定已经实现的功能代码不允许被修改,但可以被扩展,即:
 •封闭:已实现的功能代码块
 •开放:对扩展开发
如果将开放封闭原则应用在上述需求中,那么就不允许在函数 f1 ,f2,f3,f4的内部进行修改代码:

def w1(func):
    def inner():
        # 验证1
        # 验证2
        # 验证3
        func()
    return inner

@w1
def f1():
    print('f1')
@w1
def f2():
    print('f2')
@w1
def f3():
    print('f3')
@w1
def f4():
    print('f4')

对于上述代码,也是仅仅对基础平台的代码进行修改,就可以实现在其他人调用f1,f2,f3,f4 之前都进行【验证】操作,并且其他业务部门无需做任何操作。
●经过了上面的改动后,一个比较完整的装饰器(w1)就实现了,装饰器没有影响原来的函数,以及函数调用的代码。例子中值得注意的地方是,Python中一切都是对象,函数也是,所以代码中改变了”f1…”对应的函数对象。
单独以f1为例:

def w1(func):
    def inner():
        # 验证1
        # 验证2
        # 验证3
        func()
    return inner

@w1
def f1():
    print('f1')

●在Python中,可以使用”@”语法糖来精简装饰器的代码
●python解释器就会从上到下解释代码,步骤如下:
1. def w1(func):将w1函数加载到内存
2. @w1
●从表面上看解释器仅仅会解释这两句代码,因为函数在没有被调用之前其内部代码不会被执行。
●代码块@w1的内部操作:
 执行w1函数:
  执行w1函数,并将@w1下面的f1函数作为w1函数的参数,使用了‘@’语法糖后,我们就不需要额外代码来给’f1’重新赋值了,其实’@w1’的本质就是’f1= w1(f1)’.所以内部会执行:

def inner(): 
    #验证 1
    #验证 2
    #验证 3
    f1()     # func是参数,此时 func 等于 f1 
return inner # 返回inner,inner代表的是函数,非执行函数 ,其实就是将原来的f1函数塞进另外一个函数中.

 w1的返回值:
  将执行完的w1函数返回值 赋值 给@w1下面的函数的函数名f1 即将w1的返回值再重新赋值给 f1,即:
  

def inner(): #新的f1函数
    #验证 1
    #验证 2
    #验证 3
       f1()  #旧的f1函数
return inner

所以,以后业务部门想要执行 f1 函数时,就会执行 新f1 函数,在新f1 函数内部先执行验证,再执行原来的f1函数,然后将原来f1 函数的返回值返回给了业务调用者。
如此一来, 即执行了验证的功能,又执行了原来f1函数的内容,并将原f1函数返回值 返回给业务调用着

2. 多个装饰器

示例:

#定义函数:完成包裹数据
def makeBold(fn):
    def wrapped():
        return "<b>" + fn() + "</b>"
    return wrapped

#定义函数:完成包裹数据
def makeItalic(fn):
    def wrapped():
        return "<i>" + fn() + "</i>"
    return wrapped

@makeBold
def test1():
    return "hello world-1"

@makeItalic
def test2():
    return "hello world-2"

@makeBold
@makeItalic
def test3():
    return "hello world-3"

print(test1()))
print(test2()))
print(test3()))

运行结果:

<b>hello world-1</b>
<i>hello world-2</i>
<b><i>hello world-3</i></b>

3. 装饰器示例

示例1:无参数的函数

from time import ctime

def timefun(func):
    def wrappedfunc():
        print("%s called at %s"%(func.__name__, ctime()))
        func()
    return wrappedfunc

@timefun
def foo():
    print("I am foo")

foo()

注:
func.__name__就是调用函数的foo

运行结果:

foo called at Tue Jun  6 21:42:50 2017
I am foo

上面代码理解装饰器执行行为可理解成:

foo = timefun(foo)
#foo先作为参数赋值给func后,foo接收指向timefun返回的wrappedfunc
foo()
#调用foo(),即等价调用wrappedfunc()
#内部函数wrappedfunc被引用,所以外部函数的func变量(自由变量)并没有释放
#func里保存的是原foo函数对象

示例2:被装饰的函数有参数

from time import ctime

def timefun(func):
    def wrappedfunc(a, b):
        print("%s called at %s"%(func.__name__, ctime()))
        print(a, b)
        func(a, b)
    return wrappedfunc

@timefun
def foo(a, b):
    print(a+b)

foo(3,5)

运行结果:

foo called at Tue Jun  6 21:54:33 2017
3 5
8

示例3:被装饰的函数有不定长参数

from time import ctime

def timefun(func):
    def wrappedfunc(*args,**kwargs):
        print("%s called at %s"%(func.__name__, ctime()))
        print(args, kwargs)
        return func(*args,**kwargs)
    return wrappedfunc

@timefun
def foo():
    print("I am foo")

@timefun
def foo1(a,b):
    print(a+b)

@timefun
def foo2(c,d,e):
    print(c+d-e)

@timefun
def foo3(**a_dict):
    print('........')

foo()
foo1(3,2)
foo2(5,6,4)
foo3(id=1,num='5555')

注:
*args为元组,没有key值,
**kwargs为字典,有key值
运行结果:

foo called at Tue Jun  6 21:57:52 2017
() {}
I am foo
foo1 called at Tue Jun  6 21:57:52 2017
(3, 2) {}
5
foo2 called at Tue Jun  6 21:57:52 2017
(5, 6, 4) {}
7
foo3 called at Tue Jun  6 21:57:52 2017
() {'id': 1, 'num': '5555'}
........

示例4:装饰器中的return

from time import ctime

def timefun(func):
    def wrappedfunc():
        print("%s called at %s"%(func.__name__, ctime()))
        func()  #此处添加return
    return wrappedfunc

@timefun
def foo():
    print("I am foo")

@timefun
def getInfo():
    return '----hahah---'

foo()
print(getInfo())

运行结果:

foo called at Tue Jun  6 22:00:48 2017
I am foo
getInfo called at Tue Jun  6 22:00:48 2017
None

加上return之后的运行结果:

foo called at Tue Jun  6 22:02:22 2017
I am foo
getInfo called at Tue Jun  6 22:02:22 2017
----hahah---

总结:
• 一般情况下为了让装饰器更通用,可以有return
 

示例5:装饰器带参数,在原有装饰器的基础上,设置外部变量

def decorator(num):
    def timefun(func):
        def wrappedfunc(*args,**kwargs):
            if num==1:
                print('123123')
            else:
                print('456456')
            return func(*args,**kwargs)
        return wrappedfunc
    return timefun

@decorator(1)
def foo1():
    print('hhaha')

@decorator(2)
def foo2():
    print('hhehe')

foo1()
print('*'*100)
foo2()

运行结果:

123123
hhaha
****************************************************************************************************
456456
hhehe

6.类装饰器

示例:

class Test(object):
    def __init__(self, func):
        print("---初始化---")
        print("func name is %s"%func.__name__)
        self.__func = func
    def __call__(self):
        print("---装饰器中的功能---")
        self.__func()
@Test
def test():
    print("----test---")
test()

说明:
 1. 当用Test来装作装饰器test函数进行装饰的时候,首先会创建Test的实例对象。并且会把test这个函数名当做参数传递到__init__方法中,即在__init__方法中的func变量指向了test函数体。
 2. test函数相当于指向了用Test创建出来的实例对象。
 3. 当在使用test()进行调用时,就相当于让这个对象(),因此会调用这个对象的__call__方法。
 4. 为了能够在__call__方法中调用原来test指向的函数体,所以在__init__方法中就需要一个实例属性来保存这个函数体的引用所以才有了self.__func = func这句代码,从而在调用__call__方法中能够调用到test之前的函数体。

7. property属性

7.1 私有属性添加getter和setter方法

 示例:

class Money(object):

    def __init__(self):
        self.__money = 0

    @property
    def money(self):
        print('getMoney...')
        return self.__money
    @money.setter
    def money(self, value):
        print('setMoney...')
        if isinstance(value, int):
            self.__money = value
        else:
            print("error:不是整型数字")

qian = Money()
print(qian.money)
qian.money = 100
print(qian.money)

运行结果:

getMoney...
0
setMoney...
getMoney...
100

说明:
 ●私有的属性,为了对外能访问,提供了对外访问的get,set方法;
 但是对于使用的时候稍微繁琐,使用ret=property(get,set);
当对象获取ret的时候,相当于调用了get方法,获取返回值;
当对象设置ret的时候,相当于调用set,将设置的值传递给set的方法作为实参;
 相当于一个伪装。
 ●@property成为属性函数,可以对属性赋值时做必要的检查,并保证代码的清晰短小,主要有2个作用:
  • 将方法转换为只读
  • 重新实现一个属性的设置和读取方法,可做边界判定
 ●@注解,get,set方法名字保持一致xx,在当时的get方法头部加 @property,在原来的set方法头部加@xx.setter
  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值