装饰器是Python高级应用的一部分,其应用也很广泛。
网上对其介绍和讲解也是五花八门,我在这里就对其进行简单介绍,并对如何渐进理解使用装饰器进行说明,以便和大家共同学习。
如有更高见解,也请大家留言指正。

  • 装饰器概念简单理解

  • 循序渐进装饰器


装饰器概念简单理解

  • 装饰器按照我的理解,就是在不改变原有函数代码的情况下,对原有函数进行功能的扩展。

  • 这里先写个简单的装饰器,给大家有个概念性的认识。

def anotherone(func):  #定义装饰器
    def inner():
        print('this an inner print!')
        return func()
    return inner

@anotherone
def test ():  #定义函数
    print ('this is a test print!')
test()
  • 打印结果:

    this an inner print!
    this is a test print!

  • 在上面的例子中, 函数test(),原来只有打印一个“this is a test print!”的功能,但是添加了我们的装饰器anotherone()之后。对于函数test()而言:

    • 首先没有改变原来test()函数的代码。

    • 另外,添加了另外的功能,也就是除了实现原来的功能以外,添加了打印“this an inner print!”的功能。


循序渐进装饰器

在理解了概念的同时,我们要对该装饰器进行理解,也就是为什么要这样写法呢?我们分步来说:

  • 首先看如下代码:

def test():
  print ('this is a test')
  • 执行:

test
  • 结果:

    function test at 0x000002803E3FAA60

    显示的是test函数的内存地址。函数并没有执行
    再执行:

test()
  • 结果:

    this is a test

    函数test被执行。

    这说明了什么?
    说明只输入函数test名称,也就仅仅输出函数test的地址,在此基础上,再给函数test添加括号变为test(),就可以执行test函数的功能,即打印“this is a test”。理解这里很重要哦!

  • 添加一个需求:如果我们要对函数test()增加另外一个打印功能(增加打印“’this an inner print!’”),
    并且不改变原来的test()函数,如何去做呢?

def test2(func):
  print ("this is an inner print!")
  func()
  • 执行以下:

test2(test)
  • 结果:

    this is an inner print!
    this is a test

    说明一下:定义一个函数test2(),接收的参数是test的内存地址,没有加“()”,因此在接收函数test的时候,函数test()不会被执行。引入到test2()中以后,在test2()中,先执行了“this is an inner print!”,然后对函数test加括号,变成test()执行之。


出现的问题,为了添加这个功能,所有原来使用test函数的地方,即原来“test()”现在都要改为“test2(test)”来执行。如果很多地方都要更改,不但增加了工作量,而且可能会因为疏漏造成一些问题。有什么方法可以解决呢?

解决方案:正如上面我所提到的,如果我们将原来的 test2(test)的内存地址重新赋值给一个叫test变量(亦即test=test2(test)),再加个括号,使用test()就是执行了test2(test)。  以上亦即新的test()实现了test2(test)的功能。 这里注意的是新的test()已被重新赋值,已非原来的test()了。

实现该功能步骤如下

  1. 新建一个函数anotherone(func)。

  2. func用来传入原来函数(这里是原test())的内存地址。

  3. 在anotherone(func)中新建一个函数inner()。

  4. inner()函数地址将来会被anotherone(func)返回并赋值给变量test。

  5. 执行test()完成。

  • 函数anotherone(func)框架如下:

def anotherone(func):
  def inner():
      #添加功能
return inner

我们再看一下inner()函数的构成

def inner():
    print('this is an inner print!')
    return func()
  • 首先,这里就是添加新的功能和实现原来功能的地方。比如这里添加一个打印功能“print (“this is an inner print!”)”。

  • 实现了新功能之后,使用“return”返回并执行原来函数的功能,亦即“return func()”

  • 注意:不能使用“return func”,因为我们是要返回原来函数的功能,不是返回原来函数的地址 。

最后组合一下看看源码

def anotherone(func): 
    def inner():
        print('this an inner print!')
        return func()
    return inner

def test ():
    print ('this is a test print!')

test = anotherone(test)
test()

首先是:“test = anotherone(test)”

  • 将test()函数地址传给func后,anotherone()返回了内置函数inner()的内存地址,并赋值给一个变量test,这里inner()并未被执行,仅仅是进行了赋值。


紧接着:“test()”

  • 执行新的test(),亦即执行inner():打印“’this an inner print!”,后return func(),亦即执行原来的test()功能,打印“’this is a test print!”。

正如我们所期望的输入结果如下:

this an inner print!
this is a test print!


最后,我们看的清楚,其实定义anotherone(func),亦即定义了一个装饰器。其中

@anotherone

等同于:

test = anotherone(test)


转载请注明出处。
了解更多,请关注我的微信公众号:
射手座IT俱乐部

Python之简单理解装饰器(1)_ 装饰器