Python 中的生成器和装饰器是什么?

pythonserver side programmingprogramming更新于 2025/4/29 4:28:17

在本文中,我们将向您解释 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 循环和 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 函数,它在另一个 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 来修改它的实际函数。

装饰器返回包装器函数。

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 中的生成器和装饰器。我们还演示了如何在编写代码时使用生成器和装饰器。


相关文章


有用资源