首頁  >  文章  >  後端開發  >  生成器和裝飾器在Python中是什麼?

生成器和裝飾器在Python中是什麼?

王林
王林轉載
2023-09-10 22:49:02966瀏覽

生成器和裝飾器在Python中是什麼?

在這篇文章中,我們將向您解釋什麼是Python中的生成器和裝飾器。

自從 PEP 255 引入生成器以來,它們一直是 Python 的重要組成部分。

Python 中的生成器是一個特殊的例程,可用來控制循環的迭代行為。生成器類似於傳回數組的函數。生成器有一個參數,我們可以呼叫它並產生一個數字序列。但與傳回整個陣列的函數不同,生成器一次產生一個值,需要更少的記憶體。

任何帶有關鍵字「yield」的Python函數都可以稱為生成器。普通的 python 函數從第一行開始執行,並繼續執行,直到我們收到 return 語句或異常或函數結束,但是,在函數作用域期間創建的任何局部變數都將被銷毀,並且無法進一步存取。而對於生成器來說,當它遇到yield關鍵字時,函數的狀態將被凍結,並且所有變數都將儲存在記憶體中,直到再次呼叫生成器。

我們可以根據迭代器使用生成器,也可以使用「next」關鍵字明確呼叫。

通常是 Python 中的生成器 -

  • 使用 def 關鍵字定義

  • 使用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是一個可呼叫函數,它在另一個可呼叫函數python_decorator之上添加一些程式碼並傳回包裝函數。 p>

範例

這裡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 中的生成器和裝飾器。我們也示範如何在編寫程式碼時使用生成器和裝飾器。

以上是生成器和裝飾器在Python中是什麼?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除