Python 生成器和装饰器是什么

Python 生成器和装饰器是什么

在本文中,我们将向您解释Python中的生成器和装饰器是什么。

自从PEP 255引入以来,生成器一直是Python的重要组成部分。

在Python中,生成器是一种特殊的例程,可以用来控制循环的迭代行为。生成器类似于返回数组的函数。生成器有一个参数,我们可以调用它并生成一系列数字。但与返回整个数组的函数不同的是,生成器一次生成一个值,这样可以节省内存。

任何带有关键字“yield”的Python函数都可以称为生成器。普通的Python函数从第一行开始执行,直到遇到return语句、异常或函数的结尾,然后在函数作用域内创建的所有局部变量都被销毁并且无法再访问。而对于生成器来说,当它遇到yield关键字时,函数的状态会被冻结,并且所有的变量都存储在内存中,直到再次调用生成器。

我们可以将生成器与迭代器一起使用,或者可以使用“ next ”关键字来显式调用生成器。

一般来说,Python中的生成器:

  • 使用def关键字进行定义
  • 使用yield关键字
  • 可能包含多个yield关键字
  • 返回一个迭代器

生成器 是返回一个 可迭代 的生成器对象的函数。因为从生成器对象获取的值是一个一个获取的,而不是一次获取整个列表,所以可以使用for循环、next()函数或list()函数来获取实际的值。

生成器函数

可以使用生成器函数和生成器表达式来创建生成器。

生成器函数类似于普通函数,但是它不返回一个值,而是使用yield关键字。

要创建一个生成器函数,添加 yield 关键字。下面的示例演示了如何编写一个生成器函数。

具有迭代器的生成器

示例

# creating a function
def generatorExample():
   yield "T"
   yield "U"
   yield "T"
   yield "O"
   yield "R"
   yield "I"
   yield "A"
   yield "L"
   yield "S"
# calling the generatorExample() function which is created above
result = generatorExample()
# Traversing in the above result(generator object)
for k in result:
   # Printing the corresponding value
   print(k)

输出

T
U
T
O
R
I
A
L
S

从生成器中读取产量值

可以使用list()、for-loop和next()方法从生成器对象中读取值。

使用next()从生成器对象中读取值

next()方法返回列表、数组或对象中的下一项。当列表为空且调用next()时,它会返回一个带有StopIteration信号的错误。该错误表示列表中没有更多的项。

示例

# creating a function that accepts a number as an argument
def oddNumbers(num):
   # traversing till that number passed
   for i in range(num):
      # checking whether the iterator index value is an odd number
      if (i%2!=0):
         # getting the iterator index value if the condition is true using the yield keyword
         yield i
# calling the above function to get the odd numbers below 8
result = oddNumbers(8)
# calling the next items in the result list
print(next(result))
print(next(result))
print(next(result))
print(next(result))
# throws an error since the list has no more elements
print(next(result))

输出

1
3
5
7
Traceback (most recent call last):
File "main.py", line 17, in <module>
    print(next(result))
StopIteration

Python中的装饰器

Python提供了一个令人惊叹的工具,叫做 装饰器 用于给现有代码添加功能。

这也被称为 元编程 因为程序的一部分在编译时尝试修改另一部分程序。

装饰器将函数作为参数传递给另一个函数,并在包装函数中调用该函数。

语法

@tutorials_decorator
def python_decorator():
   print("Hello tutorials Point")
'''Above code is equivalent to -
def python_decorator():
   print("Hello tutorials Point")
python_decorator = tutorials_decorator(python_decorator)'''

在这里, tutorials_decorator 是一个可调用函数,它在另一个 callable 函数 python_decorator 的顶部添加一些代码,并返回包装函数。

示例

这里 func 是被装饰的函数, python_decorator 是用来装饰它的函数。

# defining a decorator
def python_decorator(func):
   def wrapper():
      print("Text before calling the function")
      func()
      print("Text after calling the function")
   return wrapper
def tutorials_decorator():
   print("Hello tutorials Point!!!")
tutorials_decorator = python_decorator(tutorials_decorator)
tutorials_decorator()

输出

Text before calling the function
Hello tutorials Point!!!
Text after calling the function

python_decorator(func) − 这是一个装饰器函数;它接受另一个函数作为参数,并“装饰”它,这意味着它修改了它并返回修改后的版本。

wrapper − 在装饰器函数中,我们定义了另一个名为 wrapper 的内部函数。这是实际上修改传递的函数 func 的函数。

装饰器函数返回wrapper函数。

tutorials_decorator − 这是一个我们需要装饰的普通函数。它只在这里打印一个简单的声明。

语法装饰器

上述的装饰器模式在Python社区中变得流行,但是它有点复杂。我们必须三次写函数名,并且装饰对函数定义进行了隐藏。

因此,Python通过在 @符号 中包含语法糖来添加使用装饰器的新方法。 –

语法

@decorator
def func(arg1, arg2, ...):
   pass

语法糖是编程语言中使用的一种语法,用于使阅读或表达更加容易。

示例

下面的示例执行与前一个示例相同的操作−

# defining a decorator
def python_decorator(func):
   def wrapper():
      print("Text before calling the function")
      func()
      print("Text after calling the function")
   return wrapper
@python_decorator
def tutorials_decorator():
   print("Hello tutorials Point!!!")
tutorials_decorator()

输出

Text before calling the function
Hello tutorials Point!!!
Text after calling the function

和之前的示例一样,唯一的区别是我们使用 @python_decorator 而不是

tutorials_decorator = python_decorator(tutorials_decorator)

结论

在本文中,我们简要介绍了Python中的生成器和装饰器。我们还演示了如何在编写代码时使用生成器和装饰器。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程