Python Decorator示例

时间:2020-02-23 14:42:37  来源:igfitidea点击:

Python装饰器是一个有助于向已定义函数添加一些其他功能的函数。
Python装饰器在不对原始功能进行任何更改的情况下将功能添加到之前实现的功能中非常有用。
想要将更新的代码提供给现有代码时,Decorator非常有效。

Python装饰器

希望大家都很好,并在python上度过了愉快的时光。
今天我们将学习python装饰器。
正如我之前定义的,python装饰器不过是装饰函数的装饰器。
例如,您家中有一个花瓶。
现在,您想用一些花和一些装饰品来装饰它。
然后,您将被称为装饰器,而花和装饰品将被称为附加功能。

Python Decorator基本结构

让我们看一下python装饰器函数的基本结构。

# example of decorator
def sampleDecorator(func):
  def addingFunction():
      # some new statments or flow control
      print("This is the added text to the actual function.")
      # calling the function
      func()

  return addingFunction

@sampleDecorator
def actualFunction():
  print("This is the actual function.")

actualFunction()

上面的代码将产生以下输出:

This is the added text to the actual function.
This is the actual function.

在上面的代码中,第12行有一个特殊字符@,主要表示在其正下方定义的函数将使用sampleDecorator函数进行修饰。

上面的代码可以解释为以下代码假定我们没有第12行。
然后,如果要获得相同的样式,则必须重写第17行,如下所示:

actualFunction = sampleDecorator(actualFunction)
actualFunction()

然后,您将获得与以前相同的输出。
观察以上两行,您可以假设什么?我们主要是在使用" sampleDecorator"函数覆盖"actualFunction"函数的情况下,将" actualFunction"作为装饰函数的参数传递给我们。

带有单个参数的Python Decorator示例

考虑下面的代码,我们要装饰的函数确实有一个参数。
注意我们如何实现装饰器python方法。
记住花瓶的例子。
我们将提供想要放入的花朵数量。

def flowerDecorator(vasel):
  def newFlowerVase(n):
      print("We are decorating the flower vase.")
      print("You wanted to keep %d flowers in the vase." % n)

      vasel(n)

      print("Our decoration is done")

  return newFlowerVase

@flowerDecorator
def flowerVase(n):
  print("We have a flower vase.")

flowerVase(6)

你能假设输出吗?上面代码的输出将是:

We are decorating the flower vase.
You wanted to keep 6 flowers in the vase.
We have a flower vase.
Our decoration is done

了解python装饰器参数代码

现在,让我们模拟上面的代码。
首先在第18行中,我们将函数称为" flowerVase(6)"。
然后流程转到第13行,并看到此函数正在由另一个名为" flowerDecorator"的函数修饰。
因此,它转到第1行,其中将flowerflower作为参数发送。

请注意,flowerVase具有一个参数。
在" flowerDecorator"函数中,我们定义了一个名为" newFlowerVase"的新函数,该函数将软件包实际函数,并注意该函数将具有与实际函数(flowerVase)完全相同的数字或者参数。

然后,我们向其中添加一些新功能(打印一些消息),并调用带有参数的实际函数,该参数已作为参数发送给" flowerDecorator"。
最后,我们返回第18行接收到的" newFlowerVase",并在装饰它时得到输出。

这就是python函数装饰器的工作方式。
如果您的实际函数具有多个参数,那么装饰器的内部函数将具有相同数量的参数。

Python Decorator Example处理异常

以下代码将打印数组相对于其索引的值。

array = ['a', 'b', 'c']
def valueOf(index):
 print(array[index])
valueOf(0)

这将输出:

a

但是如果我们调用该函数,

valueOf(10)

这将输出:

Traceback (most recent call last):
File "D:/T_Code/Pythongenerator/array.py", line 4, in 
  valueOf(10)
File "D:/T_Code/Pythongenerator/array.py", line 3, in valueOf
  print(array[index])
IndexError: list index out of range

由于我们尚未处理给定的索引值是否超过数组的大小。
因此,现在我们将装饰该功能如下:

array = ['a', 'b', 'c']

def decorator(func):
  def newValueOf(pos):
      if pos >= len(array):
          print("Oops! Array index is out of range")
          return
      func(pos)

  return newValueOf

@decorator
def valueOf(index):
  print(array[index])

valueOf(10)

现在我们已经处理了数组异常超出范围的可能错误。