Hướng dẫn does it matter where a function is defined in python? - có vấn đề gì khi một chức năng được xác định trong python không?

Không quan trọng trong việc đặt hàng các chức năng được tạo. Nó chỉ quan trọng khi cuộc gọi đến chức năng được thực hiện:

Show
def print_sum(a, b):
    print(sum_numbers(a, b))

def sum_numbers(a, b):
    return a + b

print_sum(1, 3)
# 4

Điều đó hoạt động bởi vì tại thời điểm

def print_sum(a, b):
    print(sum_numbers(a, b))

print_sum(1, 3)

def sum_numbers(a, b):
    return a + b
9 được gọi là cả hai chức năng tồn tại. Tuy nhiên, nếu bạn gọi chức năng trước khi xác định
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-34-37c0e3733861> in <module>()
      2     print(sum_numbers(a, b))
      3 
----> 4 print_sum(1, 3)
      5 
      6 def sum_numbers(a, b):

<ipython-input-34-37c0e3733861> in print_sum(a, b)
      1 def print_sum(a, b):
----> 2     print(sum_numbers(a, b))
      3 
      4 print_sum(1, 3)
      5 

NameError: name 'sum_numbers' is not defined
0, nó sẽ thất bại vì
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-34-37c0e3733861> in <module>()
      2     print(sum_numbers(a, b))
      3 
----> 4 print_sum(1, 3)
      5 
      6 def sum_numbers(a, b):

<ipython-input-34-37c0e3733861> in print_sum(a, b)
      1 def print_sum(a, b):
----> 2     print(sum_numbers(a, b))
      3 
      4 print_sum(1, 3)
      5 

NameError: name 'sum_numbers' is not defined
0 chưa được xác định:

def print_sum(a, b):
    print(sum_numbers(a, b))

print_sum(1, 3)

def sum_numbers(a, b):
    return a + b

throws:

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-34-37c0e3733861> in <module>()
      2     print(sum_numbers(a, b))
      3 
----> 4 print_sum(1, 3)
      5 
      6 def sum_numbers(a, b):

<ipython-input-34-37c0e3733861> in print_sum(a, b)
      1 def print_sum(a, b):
----> 2     print(sum_numbers(a, b))
      3 
      4 print_sum(1, 3)
      5 

NameError: name 'sum_numbers' is not defined

Xem bây giờ hướng dẫn này có một khóa học video liên quan được tạo bởi nhóm Python thực sự. Xem nó cùng với hướng dẫn bằng văn bản để làm sâu sắc thêm sự hiểu biết của bạn: các chức năng bên trong của Python This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Python Inner Functions

Chức năng nên được xác định ở đâu trong Python?, also known as nested functions, are functions that you define inside other functions. In Python, this kind of function has direct access to variables and names defined in the enclosing function. Inner functions have many uses, most notably as closure factories and decorator functions.

Cú pháp cơ bản Để xác định một hàm trong Python trong Python, bạn xác định một hàm với từ khóa DEF, sau đó viết định danh chức năng (tên) theo sau là dấu ngoặc đơn và dấu hai chấm. Điều tiếp theo bạn phải làm là đảm bảo bạn thụt lề với một tab hoặc 4 khoảng trống, sau đó chỉ định những gì bạn muốn chức năng làm cho bạn.

  • Bạn có thể xác định các chức năng ở bất cứ đâu trong Python không?encapsulation and hide your functions from external access
  • Bất cứ nơi nào trong ứng dụng của bạn mà bạn cần hoàn thành nhiệm vụ, bạn chỉ cần gọi chức năng. Xuống dòng, nếu bạn quyết định thay đổi cách thức hoạt động, thì bạn chỉ cần thay đổi mã ở một vị trí, đó là nơi xác định hàm.helper functions to facilitate code reuse
  • Thứ tự chức năng có quan trọng Python không?closure factory functions that retain state between calls
  • Không quan trọng chúng được đưa ra theo thứ tự nào trong tham số miễn là các đối số trong biểu thức cuộc gọi phù hợp với biến chính xác. Dù bằng cách nào sẽ không quan trọng với chuỗi đầu ra.decorator functions to add behavior to existing functions

Nên chức năng chính ở trên cùng hoặc dưới cùng?

Công ước thông thường là đặt chúng ở cuối kịch bản. Và tất nhiên bạn không thể gọi chính trước khi xác định nó.inner function or a nested function. In Python, this kind of function can access names in the enclosing function. Here’s an example of how to create an inner function in Python:

>>>

>>> def outer_func():
...     def inner_func():
...         print("Hello, World!")
...     inner_func()
...

>>> outer_func()
Hello, World!

Các chức năng bên trong, còn được gọi là các hàm lồng nhau, là các hàm mà bạn xác định bên trong các chức năng khác. Trong Python, loại chức năng này có quyền truy cập trực tiếp vào các biến và tên được xác định trong hàm kèm theo. Các chức năng bên trong có nhiều cách sử dụng, đáng chú ý nhất là các nhà máy đóng cửa và chức năng trang trí.

Trong hướng dẫn này, bạn sẽ học cách:

>>>

>>> def outer_func(who):
...     def inner_func():
...         print(f"Hello, {who}")
...     inner_func()
...

>>> outer_func("World!")
Hello, World!

Cung cấp đóng gói và ẩn các chức năng của bạn khỏi quyền truy cập bên ngoàinonlocal names. They are nonlocal from the

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-34-37c0e3733861> in <module>()
      2     print(sum_numbers(a, b))
      3 
----> 4 print_sum(1, 3)
      5 
      6 def sum_numbers(a, b):

<ipython-input-34-37c0e3733861> in print_sum(a, b)
      1 def print_sum(a, b):
----> 2     print(sum_numbers(a, b))
      3 
      4 print_sum(1, 3)
      5 

NameError: name 'sum_numbers' is not defined
2 point of view.

Dưới đây, một ví dụ về cách tạo và sử dụng hàm bên trong phức tạp hơn:

>>>

>>> def factorial(number):
...     # Validate input
...     if not isinstance(number, int):
...         raise TypeError("Sorry. 'number' must be an integer.")
...     if number < 0:
...         raise ValueError("Sorry. 'number' must be zero or positive.")
...     # Calculate the factorial of number
...     def inner_factorial(number):
...         if number <= 1:
...             return 1
...         return number * inner_factorial(number - 1)
...     return inner_factorial(number)
...

>>> factorial(4)
24

Trong

>>> def outer_func():
...     def inner_func():
...         print("Hello, World!")
...     inner_func()
...

>>> outer_func()
Hello, World!
2, trước tiên bạn xác nhận dữ liệu đầu vào để đảm bảo rằng người dùng của bạn đang cung cấp một số nguyên bằng hoặc lớn hơn 0. Sau đó, bạn xác định hàm bên trong đệ quy gọi là
>>> def outer_func():
...     def inner_func():
...         print("Hello, World!")
...     inner_func()
...

>>> outer_func()
Hello, World!
3 thực hiện tính toán giai thừa và trả về kết quả. Bước cuối cùng là gọi
>>> def outer_func():
...     def inner_func():
...         print("Hello, World!")
...     inner_func()
...

>>> outer_func()
Hello, World!
3.

Ưu điểm chính của việc sử dụng mẫu này là, bằng cách thực hiện tất cả các đối số kiểm tra trong hàm bên ngoài, bạn có thể bỏ qua kiểm tra lỗi một cách an toàn trong hàm bên trong và tập trung vào tính toán trong tay.

Sử dụng các chức năng bên trong: những điều cơ bản

Các trường hợp sử dụng của các hàm bên trong Python rất khác nhau. Bạn có thể sử dụng chúng để cung cấp đóng gói và ẩn các chức năng của bạn khỏi quyền truy cập bên ngoài, bạn có thể viết các chức năng bên trong của người trợ giúp và bạn cũng có thể tạo các trình trang trí và trang trí. Trong phần này, bạn sẽ tìm hiểu về hai trường hợp sử dụng trước đây của các chức năng bên trong và trong các phần sau, bạn sẽ học cách tạo các chức năng và trang trí của nhà máy đóng cửa.

Cung cấp đóng gói

Một trường hợp sử dụng phổ biến của các hàm bên trong phát sinh khi bạn cần bảo vệ hoặc ẩn, một chức năng nhất định khỏi mọi thứ xảy ra bên ngoài để chức năng được ẩn hoàn toàn khỏi phạm vi toàn cầu. Loại hành vi này thường được gọi là đóng gói.encapsulation.

Ở đây, một ví dụ làm nổi bật khái niệm đó:

>>>

>>> def increment(number):
...     def inner_increment():
...         return number + 1
...     return inner_increment()
...

>>> increment(10)
11

>>> # Call inner_increment()
>>> inner_increment()
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    inner_increment()
NameError: name 'inner_increment' is not defined

Trong

>>> def outer_func():
...     def inner_func():
...         print("Hello, World!")
...     inner_func()
...

>>> outer_func()
Hello, World!
2, trước tiên bạn xác nhận dữ liệu đầu vào để đảm bảo rằng người dùng của bạn đang cung cấp một số nguyên bằng hoặc lớn hơn 0. Sau đó, bạn xác định hàm bên trong đệ quy gọi là
>>> def outer_func():
...     def inner_func():
...         print("Hello, World!")
...     inner_func()
...

>>> outer_func()
Hello, World!
3 thực hiện tính toán giai thừa và trả về kết quả. Bước cuối cùng là gọi
>>> def outer_func():
...     def inner_func():
...         print("Hello, World!")
...     inner_func()
...

>>> outer_func()
Hello, World!
3.

Ưu điểm chính của việc sử dụng mẫu này là, bằng cách thực hiện tất cả các đối số kiểm tra trong hàm bên ngoài, bạn có thể bỏ qua kiểm tra lỗi một cách an toàn trong hàm bên trong và tập trung vào tính toán trong tay.

Sử dụng các chức năng bên trong: những điều cơ bản

# hotspots.py

import csv
from collections import Counter

def process_hotspots(file):
    def most_common_provider(file_obj):
        hotspots = []
        with file_obj as csv_file:
            content = csv.DictReader(csv_file)

            for row in content:
                hotspots.append(row["Provider"])

        counter = Counter(hotspots)
        print(
            f"There are {len(hotspots)} Wi-Fi hotspots in NYC.\n"
            f"{counter.most_common(1)[0][0]} has the most with "
            f"{counter.most_common(1)[0][1]}."
        )

    if isinstance(file, str):
        # Got a string-based filepath
        file_obj = open(file, "r")
        most_common_provider(file_obj)
    else:
        # Got a file object
        most_common_provider(file)

Các trường hợp sử dụng của các hàm bên trong Python rất khác nhau. Bạn có thể sử dụng chúng để cung cấp đóng gói và ẩn các chức năng của bạn khỏi quyền truy cập bên ngoài, bạn có thể viết các chức năng bên trong của người trợ giúp và bạn cũng có thể tạo các trình trang trí và trang trí. Trong phần này, bạn sẽ tìm hiểu về hai trường hợp sử dụng trước đây của các chức năng bên trong và trong các phần sau, bạn sẽ học cách tạo các chức năng và trang trí của nhà máy đóng cửa.

  1. Cung cấp đóng gói
  2. Một trường hợp sử dụng phổ biến của các hàm bên trong phát sinh khi bạn cần bảo vệ hoặc ẩn, một chức năng nhất định khỏi mọi thứ xảy ra bên ngoài để chức năng được ẩn hoàn toàn khỏi phạm vi toàn cầu. Loại hành vi này thường được gọi là đóng gói.
  3. Ở đây, một ví dụ làm nổi bật khái niệm đó:
  4. Trong ví dụ này, bạn có thể truy cập trực tiếp vào
    >>> def outer_func():
    ...     def inner_func():
    ...         print("Hello, World!")
    ...     inner_func()
    ...
    
    >>> outer_func()
    Hello, World!
    
    5. Nếu bạn cố gắng làm điều đó, thì bạn sẽ nhận được
    >>> def outer_func():
    ...     def inner_func():
    ...         print("Hello, World!")
    ...     inner_func()
    ...
    
    >>> outer_func()
    Hello, World!
    
    6. Điều đó vì
    >>> def outer_func():
    ...     def inner_func():
    ...         print("Hello, World!")
    ...     inner_func()
    ...
    
    >>> outer_func()
    Hello, World!
    
    7 hoàn toàn ẩn
    >>> def outer_func():
    ...     def inner_func():
    ...         print("Hello, World!")
    ...     inner_func()
    ...
    
    >>> outer_func()
    Hello, World!
    
    5, ngăn bạn truy cập nó khỏi phạm vi toàn cầu.

Xây dựng các chức năng bên trong của người trợ giúp

>>>

>>> from hotspots import process_hotspots

>>> file_obj = open("./NYC_Wi-Fi_Hotspot_Locations.csv", "r")
>>> process_hotspots(file_obj)
There are 3319 Wi-Fi hotspots in NYC.
LinkNYC - Citybridge has the most with 1868.

>>> process_hotspots("./NYC_Wi-Fi_Hotspot_Locations.csv")
There are 3319 Wi-Fi hotspots in NYC.
LinkNYC - Citybridge has the most with 1868.

Đôi khi bạn có một chức năng thực hiện cùng một đoạn mã ở một số nơi trong cơ thể của nó. Ví dụ: giả sử bạn muốn viết một chức năng để xử lý tệp CSV chứa thông tin về các điểm nóng Wi-Fi ở thành phố New York. Để tìm tổng số điểm nóng ở New York cũng như công ty cung cấp hầu hết trong số họ, bạn tạo ra tập lệnh sau:

Ở đây, >>> def outer_func(): ... def inner_func(): ... print("Hello, World!") ... inner_func() ... >>> outer_func() Hello, World! 9 lấy >>> def outer_func(who): ... def inner_func(): ... print(f"Hello, {who}") ... inner_func() ... >>> outer_func("World!") Hello, World! 0 làm đối số. Hàm kiểm tra xem >>> def outer_func(who): ... def inner_func(): ... print(f"Hello, {who}") ... inner_func() ... >>> outer_func("World!") Hello, World! 0 là đường dẫn dựa trên chuỗi đến tệp vật lý hoặc đối tượng tệp. Sau đó, nó gọi hàm bên trong trợ giúp >>> def outer_func(who): ... def inner_func(): ... print(f"Hello, {who}") ... inner_func() ... >>> outer_func("World!") Hello, World! 2, lấy một đối tượng tệp và thực hiện các hoạt động sau:

Đọc nội dung tệp vào một trình tạo mang lại từ điển bằng cách sử dụng

>>> def outer_func(who):
...     def inner_func():
...         print(f"Hello, {who}")
...     inner_func()
...

>>> outer_func("World!")
Hello, World!
3.

Tạo một danh sách các nhà cung cấp Wi-Fi.

Đếm số lượng điểm nóng Wi-Fi trên mỗi nhà cung cấp bằng đối tượng

>>> def outer_func(who):
...     def inner_func():
...         print(f"Hello, {who}")
...     inner_func()
...

>>> outer_func("World!")
Hello, World!
4.

In một tin nhắn với thông tin được truy xuất.

Nếu bạn chạy chức năng, thì bạn sẽ nhận được đầu ra sau:

Cho dù bạn gọi

>>> def outer_func():
...     def inner_func():
...         print("Hello, World!")
...     inner_func()
...

>>> outer_func()
Hello, World!
9 với đường dẫn tệp dựa trên chuỗi hoặc với đối tượng tệp, bạn sẽ nhận được kết quả tương tự.Higher-order functions are functions that operate on other functions by taking them as arguments, returning them, or both.

Sử dụng các chức năng của người trợ giúp bên trong và bên trong

Thông thường, bạn tạo các hàm bên trong trợ giúp như

>>> def outer_func(who):
...     def inner_func():
...         print(f"Hello, {who}")
...     inner_func()
...

>>> outer_func("World!")
Hello, World!
2 khi bạn muốn cung cấp đóng gói. Bạn cũng có thể tạo các chức năng bên trong nếu bạn nghĩ rằng bạn sẽ không gọi chúng ở bất cứ nơi nào khác ngoài chức năng chứa.closure factory functions. Closures are dynamically created functions that are returned by other functions. Their main feature is that they have full access to the variables and names defined in the local namespace where the closure was created, even though the enclosing function has returned and finished executing.

Trong Python, khi bạn trả về một đối tượng hàm bên trong, trình thông dịch sẽ đóng gói chức năng cùng với môi trường chứa hoặc đóng của nó. Đối tượng hàm giữ một ảnh chụp nhanh của tất cả các biến và tên được xác định trong phạm vi chứa của nó. Để xác định đóng cửa, bạn cần thực hiện ba bước:

  1. Tạo một hàm bên trong.
  2. Các biến tham chiếu từ hàm kèm theo.
  3. Trả về hàm bên trong.

Với kiến ​​thức cơ bản này, bạn có thể bắt đầu tạo sự đóng cửa của mình ngay lập tức và tận dụng tính năng chính của chúng: giữ trạng thái giữa các cuộc gọi chức năng.retaining state between function calls.

Giữ lại trạng thái đóng cửa

Việc đóng cửa làm cho chức năng bên trong giữ lại trạng thái của môi trường khi được gọi. Việc đóng cửa không phải là chức năng bên trong nhưng chức năng bên trong cùng với môi trường bao quanh của nó. Việc đóng nắm bắt các biến cục bộ và tên trong hàm chứa và giữ chúng xung quanh.

Xem xét ví dụ sau:

 1# powers.py
 2
 3def generate_power(exponent):
 4    def power(base):
 5        return base ** exponent
 6    return power

Ở đây, những gì mà xảy ra trong chức năng này:

  • Dòng 3 tạo ra
    >>> def outer_func(who):
    ...     def inner_func():
    ...         print(f"Hello, {who}")
    ...     inner_func()
    ...
    
    >>> outer_func("World!")
    Hello, World!
    
    8, là chức năng của nhà máy đóng cửa. Điều này có nghĩa là nó tạo ra một đóng cửa mới mỗi khi nó gọi và sau đó trả lại cho người gọi.
    creates
    >>> def outer_func(who):
    ...     def inner_func():
    ...         print(f"Hello, {who}")
    ...     inner_func()
    ...
    
    >>> outer_func("World!")
    Hello, World!
    
    8, which is a closure factory function. This means that it creates a new closure each time it’s called and then returns it to the caller.
  • Dòng 4 xác định
    >>> def outer_func(who):
    ...     def inner_func():
    ...         print(f"Hello, {who}")
    ...     inner_func()
    ...
    
    >>> outer_func("World!")
    Hello, World!
    
    9, là hàm bên trong có một đối số duy nhất,
    >>> def factorial(number):
    ...     # Validate input
    ...     if not isinstance(number, int):
    ...         raise TypeError("Sorry. 'number' must be an integer.")
    ...     if number < 0:
    ...         raise ValueError("Sorry. 'number' must be zero or positive.")
    ...     # Calculate the factorial of number
    ...     def inner_factorial(number):
    ...         if number <= 1:
    ...             return 1
    ...         return number * inner_factorial(number - 1)
    ...     return inner_factorial(number)
    ...
    
    >>> factorial(4)
    24
    
    0 và trả về kết quả của biểu thức
    >>> def factorial(number):
    ...     # Validate input
    ...     if not isinstance(number, int):
    ...         raise TypeError("Sorry. 'number' must be an integer.")
    ...     if number < 0:
    ...         raise ValueError("Sorry. 'number' must be zero or positive.")
    ...     # Calculate the factorial of number
    ...     def inner_factorial(number):
    ...         if number <= 1:
    ...             return 1
    ...         return number * inner_factorial(number - 1)
    ...     return inner_factorial(number)
    ...
    
    >>> factorial(4)
    24
    
    1.
    defines
    >>> def outer_func(who):
    ...     def inner_func():
    ...         print(f"Hello, {who}")
    ...     inner_func()
    ...
    
    >>> outer_func("World!")
    Hello, World!
    
    9, which is an inner function that takes a single argument,
    >>> def factorial(number):
    ...     # Validate input
    ...     if not isinstance(number, int):
    ...         raise TypeError("Sorry. 'number' must be an integer.")
    ...     if number < 0:
    ...         raise ValueError("Sorry. 'number' must be zero or positive.")
    ...     # Calculate the factorial of number
    ...     def inner_factorial(number):
    ...         if number <= 1:
    ...             return 1
    ...         return number * inner_factorial(number - 1)
    ...     return inner_factorial(number)
    ...
    
    >>> factorial(4)
    24
    
    0, and returns the result of the expression
    >>> def factorial(number):
    ...     # Validate input
    ...     if not isinstance(number, int):
    ...         raise TypeError("Sorry. 'number' must be an integer.")
    ...     if number < 0:
    ...         raise ValueError("Sorry. 'number' must be zero or positive.")
    ...     # Calculate the factorial of number
    ...     def inner_factorial(number):
    ...         if number <= 1:
    ...             return 1
    ...         return number * inner_factorial(number - 1)
    ...     return inner_factorial(number)
    ...
    
    >>> factorial(4)
    24
    
    1.
  • Dòng 6 trả về
    >>> def factorial(number):
    ...     # Validate input
    ...     if not isinstance(number, int):
    ...         raise TypeError("Sorry. 'number' must be an integer.")
    ...     if number < 0:
    ...         raise ValueError("Sorry. 'number' must be zero or positive.")
    ...     # Calculate the factorial of number
    ...     def inner_factorial(number):
    ...         if number <= 1:
    ...             return 1
    ...         return number * inner_factorial(number - 1)
    ...     return inner_factorial(number)
    ...
    
    >>> factorial(4)
    24
    
    2 dưới dạng đối tượng hàm, mà không gọi nó.
    returns
    >>> def factorial(number):
    ...     # Validate input
    ...     if not isinstance(number, int):
    ...         raise TypeError("Sorry. 'number' must be an integer.")
    ...     if number < 0:
    ...         raise ValueError("Sorry. 'number' must be zero or positive.")
    ...     # Calculate the factorial of number
    ...     def inner_factorial(number):
    ...         if number <= 1:
    ...             return 1
    ...         return number * inner_factorial(number - 1)
    ...     return inner_factorial(number)
    ...
    
    >>> factorial(4)
    24
    
    2 as a function object, without calling it.

>>> def outer_func(who):
...     def inner_func():
...         print(f"Hello, {who}")
...     inner_func()
...

>>> outer_func("World!")
Hello, World!
9 nhận được giá trị của
>>> def factorial(number):
...     # Validate input
...     if not isinstance(number, int):
...         raise TypeError("Sorry. 'number' must be an integer.")
...     if number < 0:
...         raise ValueError("Sorry. 'number' must be zero or positive.")
...     # Calculate the factorial of number
...     def inner_factorial(number):
...         if number <= 1:
...             return 1
...         return number * inner_factorial(number - 1)
...     return inner_factorial(number)
...

>>> factorial(4)
24
4 từ đâu? Đây là nơi đóng cửa đi vào chơi. Trong ví dụ này,
>>> def outer_func(who):
...     def inner_func():
...         print(f"Hello, {who}")
...     inner_func()
...

>>> outer_func("World!")
Hello, World!
9 nhận được giá trị của
>>> def factorial(number):
...     # Validate input
...     if not isinstance(number, int):
...         raise TypeError("Sorry. 'number' must be an integer.")
...     if number < 0:
...         raise ValueError("Sorry. 'number' must be zero or positive.")
...     # Calculate the factorial of number
...     def inner_factorial(number):
...         if number <= 1:
...             return 1
...         return number * inner_factorial(number - 1)
...     return inner_factorial(number)
...

>>> factorial(4)
24
4 từ hàm bên ngoài,
>>> def outer_func(who):
...     def inner_func():
...         print(f"Hello, {who}")
...     inner_func()
...

>>> outer_func("World!")
Hello, World!
8. Ở đây, những gì Python làm khi bạn gọi
>>> def outer_func(who):
...     def inner_func():
...         print(f"Hello, {who}")
...     inner_func()
...

>>> outer_func("World!")
Hello, World!
8:

  1. Xác định một thể hiện mới của
    >>> def outer_func(who):
    ...     def inner_func():
    ...         print(f"Hello, {who}")
    ...     inner_func()
    ...
    
    >>> outer_func("World!")
    Hello, World!
    
    9, có một đối số duy nhất
    >>> def factorial(number):
    ...     # Validate input
    ...     if not isinstance(number, int):
    ...         raise TypeError("Sorry. 'number' must be an integer.")
    ...     if number < 0:
    ...         raise ValueError("Sorry. 'number' must be zero or positive.")
    ...     # Calculate the factorial of number
    ...     def inner_factorial(number):
    ...         if number <= 1:
    ...             return 1
    ...         return number * inner_factorial(number - 1)
    ...     return inner_factorial(number)
    ...
    
    >>> factorial(4)
    24
    
    0.
  2. Chụp ảnh chụp nhanh về trạng thái xung quanh
    >>> def outer_func(who):
    ...     def inner_func():
    ...         print(f"Hello, {who}")
    ...     inner_func()
    ...
    
    >>> outer_func("World!")
    Hello, World!
    
    9, bao gồm
    >>> def factorial(number):
    ...     # Validate input
    ...     if not isinstance(number, int):
    ...         raise TypeError("Sorry. 'number' must be an integer.")
    ...     if number < 0:
    ...         raise ValueError("Sorry. 'number' must be zero or positive.")
    ...     # Calculate the factorial of number
    ...     def inner_factorial(number):
    ...         if number <= 1:
    ...             return 1
    ...         return number * inner_factorial(number - 1)
    ...     return inner_factorial(number)
    ...
    
    >>> factorial(4)
    24
    
    4 với giá trị hiện tại của nó.
  3. Trả lại
    >>> def outer_func(who):
    ...     def inner_func():
    ...         print(f"Hello, {who}")
    ...     inner_func()
    ...
    
    >>> outer_func("World!")
    Hello, World!
    
    9 cùng với toàn bộ trạng thái xung quanh.

Bằng cách này, khi bạn gọi phiên bản của

>>> def outer_func(who):
...     def inner_func():
...         print(f"Hello, {who}")
...     inner_func()
...

>>> outer_func("World!")
Hello, World!
9 được trả về bởi
>>> def outer_func(who):
...     def inner_func():
...         print(f"Hello, {who}")
...     inner_func()
...

>>> outer_func("World!")
Hello, World!
8, bạn sẽ thấy rằng hàm này nhớ lại giá trị của
>>> def factorial(number):
...     # Validate input
...     if not isinstance(number, int):
...         raise TypeError("Sorry. 'number' must be an integer.")
...     if number < 0:
...         raise ValueError("Sorry. 'number' must be zero or positive.")
...     # Calculate the factorial of number
...     def inner_factorial(number):
...         if number <= 1:
...             return 1
...         return number * inner_factorial(number - 1)
...     return inner_factorial(number)
...

>>> factorial(4)
24
4:

>>>

def print_sum(a, b):
    print(sum_numbers(a, b))

print_sum(1, 3)

def sum_numbers(a, b):
    return a + b
0

Trong các ví dụ này,

>>> def increment(number):
...     def inner_increment():
...         return number + 1
...     return inner_increment()
...

>>> increment(10)
11

>>> # Call inner_increment()
>>> inner_increment()
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    inner_increment()
NameError: name 'inner_increment' is not defined
7 nhớ rằng
>>> def increment(number):
...     def inner_increment():
...         return number + 1
...     return inner_increment()
...

>>> increment(10)
11

>>> # Call inner_increment()
>>> inner_increment()
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    inner_increment()
NameError: name 'inner_increment' is not defined
8 và
>>> def increment(number):
...     def inner_increment():
...         return number + 1
...     return inner_increment()
...

>>> increment(10)
11

>>> # Call inner_increment()
>>> inner_increment()
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    inner_increment()
NameError: name 'inner_increment' is not defined
9 nhớ rằng
# hotspots.py

import csv
from collections import Counter

def process_hotspots(file):
    def most_common_provider(file_obj):
        hotspots = []
        with file_obj as csv_file:
            content = csv.DictReader(csv_file)

            for row in content:
                hotspots.append(row["Provider"])

        counter = Counter(hotspots)
        print(
            f"There are {len(hotspots)} Wi-Fi hotspots in NYC.\n"
            f"{counter.most_common(1)[0][0]} has the most with "
            f"{counter.most_common(1)[0][1]}."
        )

    if isinstance(file, str):
        # Got a string-based filepath
        file_obj = open(file, "r")
        most_common_provider(file_obj)
    else:
        # Got a file object
        most_common_provider(file)
0. Lưu ý rằng cả hai đóng cửa đều nhớ
>>> def factorial(number):
...     # Validate input
...     if not isinstance(number, int):
...         raise TypeError("Sorry. 'number' must be an integer.")
...     if number < 0:
...         raise ValueError("Sorry. 'number' must be zero or positive.")
...     # Calculate the factorial of number
...     def inner_factorial(number):
...         if number <= 1:
...             return 1
...         return number * inner_factorial(number - 1)
...     return inner_factorial(number)
...

>>> factorial(4)
24
4 tương ứng giữa các cuộc gọi.

Bây giờ hãy xem xét một ví dụ khác:

>>>

def print_sum(a, b):
    print(sum_numbers(a, b))

print_sum(1, 3)

def sum_numbers(a, b):
    return a + b
1

Trong các ví dụ này,

>>> def increment(number):
...     def inner_increment():
...         return number + 1
...     return inner_increment()
...

>>> increment(10)
11

>>> # Call inner_increment()
>>> inner_increment()
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    inner_increment()
NameError: name 'inner_increment' is not defined
7 nhớ rằng
>>> def increment(number):
...     def inner_increment():
...         return number + 1
...     return inner_increment()
...

>>> increment(10)
11

>>> # Call inner_increment()
>>> inner_increment()
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    inner_increment()
NameError: name 'inner_increment' is not defined
8 và
>>> def increment(number):
...     def inner_increment():
...         return number + 1
...     return inner_increment()
...

>>> increment(10)
11

>>> # Call inner_increment()
>>> inner_increment()
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    inner_increment()
NameError: name 'inner_increment' is not defined
9 nhớ rằng
# hotspots.py

import csv
from collections import Counter

def process_hotspots(file):
    def most_common_provider(file_obj):
        hotspots = []
        with file_obj as csv_file:
            content = csv.DictReader(csv_file)

            for row in content:
                hotspots.append(row["Provider"])

        counter = Counter(hotspots)
        print(
            f"There are {len(hotspots)} Wi-Fi hotspots in NYC.\n"
            f"{counter.most_common(1)[0][0]} has the most with "
            f"{counter.most_common(1)[0][1]}."
        )

    if isinstance(file, str):
        # Got a string-based filepath
        file_obj = open(file, "r")
        most_common_provider(file_obj)
    else:
        # Got a file object
        most_common_provider(file)
0. Lưu ý rằng cả hai đóng cửa đều nhớ
>>> def factorial(number):
...     # Validate input
...     if not isinstance(number, int):
...         raise TypeError("Sorry. 'number' must be an integer.")
...     if number < 0:
...         raise ValueError("Sorry. 'number' must be zero or positive.")
...     # Calculate the factorial of number
...     def inner_factorial(number):
...         if number <= 1:
...             return 1
...         return number * inner_factorial(number - 1)
...     return inner_factorial(number)
...

>>> factorial(4)
24
4 tương ứng giữa các cuộc gọi.

Bây giờ hãy xem xét một ví dụ khác:

Hàm bên trong kiểm tra xem một người dùng nhất định có quyền truy cập chính xác để truy cập một trang nhất định. Bạn có thể nhanh chóng sửa đổi điều này để lấy người dùng trong phiên để kiểm tra xem họ có thông tin đăng nhập chính xác để truy cập một tuyến đường nhất định không.static enclosing state, as you saw in the above examples. However, you can also create closures that modify their enclosing state by using mutable objects, such as dictionaries, sets, or lists.

Thay vì kiểm tra xem người dùng có bằng

# hotspots.py

import csv
from collections import Counter

def process_hotspots(file):
    def most_common_provider(file_obj):
        hotspots = []
        with file_obj as csv_file:
            content = csv.DictReader(csv_file)

            for row in content:
                hotspots.append(row["Provider"])

        counter = Counter(hotspots)
        print(
            f"There are {len(hotspots)} Wi-Fi hotspots in NYC.\n"
            f"{counter.most_common(1)[0][0]} has the most with "
            f"{counter.most_common(1)[0][1]}."
        )

    if isinstance(file, str):
        # Got a string-based filepath
        file_obj = open(file, "r")
        most_common_provider(file_obj)
    else:
        # Got a file object
        most_common_provider(file)
2 hay không, bạn có thể truy vấn cơ sở dữ liệu SQL để kiểm tra quyền và sau đó trả về chế độ xem chính xác tùy thuộc vào việc thông tin đăng nhập có chính xác hay không.

>>>

Trong các ví dụ này,
>>> def increment(number):
...     def inner_increment():
...         return number + 1
...     return inner_increment()
...

>>> increment(10)
11

>>> # Call inner_increment()
>>> inner_increment()
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    inner_increment()
NameError: name 'inner_increment' is not defined
7 nhớ rằng
>>> def increment(number):
...     def inner_increment():
...         return number + 1
...     return inner_increment()
...

>>> increment(10)
11

>>> # Call inner_increment()
>>> inner_increment()
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    inner_increment()
NameError: name 'inner_increment' is not defined
8 và
>>> def increment(number):
...     def inner_increment():
...         return number + 1
...     return inner_increment()
...

>>> increment(10)
11

>>> # Call inner_increment()
>>> inner_increment()
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    inner_increment()
NameError: name 'inner_increment' is not defined
9 nhớ rằng
# hotspots.py

import csv
from collections import Counter

def process_hotspots(file):
    def most_common_provider(file_obj):
        hotspots = []
        with file_obj as csv_file:
            content = csv.DictReader(csv_file)

            for row in content:
                hotspots.append(row["Provider"])

        counter = Counter(hotspots)
        print(
            f"There are {len(hotspots)} Wi-Fi hotspots in NYC.\n"
            f"{counter.most_common(1)[0][0]} has the most with "
            f"{counter.most_common(1)[0][1]}."
        )

    if isinstance(file, str):
        # Got a string-based filepath
        file_obj = open(file, "r")
        most_common_provider(file_obj)
    else:
        # Got a file object
        most_common_provider(file)
0. Lưu ý rằng cả hai đóng cửa đều nhớ
>>> def factorial(number):
...     # Validate input
...     if not isinstance(number, int):
...         raise TypeError("Sorry. 'number' must be an integer.")
...     if number < 0:
...         raise ValueError("Sorry. 'number' must be zero or positive.")
...     # Calculate the factorial of number
...     def inner_factorial(number):
...         if number <= 1:
...             return 1
...         return number * inner_factorial(number - 1)
...     return inner_factorial(number)
...

>>> factorial(4)
24
4 tương ứng giữa các cuộc gọi.

Bây giờ hãy xem xét một ví dụ khác:

Hàm bên trong kiểm tra xem một người dùng nhất định có quyền truy cập chính xác để truy cập một trang nhất định. Bạn có thể nhanh chóng sửa đổi điều này để lấy người dùng trong phiên để kiểm tra xem họ có thông tin đăng nhập chính xác để truy cập một tuyến đường nhất định không.

Thay vì kiểm tra xem người dùng có bằng

# hotspots.py

import csv
from collections import Counter

def process_hotspots(file):
    def most_common_provider(file_obj):
        hotspots = []
        with file_obj as csv_file:
            content = csv.DictReader(csv_file)

            for row in content:
                hotspots.append(row["Provider"])

        counter = Counter(hotspots)
        print(
            f"There are {len(hotspots)} Wi-Fi hotspots in NYC.\n"
            f"{counter.most_common(1)[0][0]} has the most with "
            f"{counter.most_common(1)[0][1]}."
        )

    if isinstance(file, str):
        # Got a string-based filepath
        file_obj = open(file, "r")
        most_common_provider(file_obj)
    else:
        # Got a file object
        most_common_provider(file)
2 hay không, bạn có thể truy vấn cơ sở dữ liệu SQL để kiểm tra quyền và sau đó trả về chế độ xem chính xác tùy thuộc vào việc thông tin đăng nhập có chính xác hay không.getter and setter inner functions for them:

>>>

def print_sum(a, b):
    print(sum_numbers(a, b))

print_sum(1, 3)

def sum_numbers(a, b):
    return a + b
3

Trong các ví dụ này,

>>> def increment(number):
...     def inner_increment():
...         return number + 1
...     return inner_increment()
...

>>> increment(10)
11

>>> # Call inner_increment()
>>> inner_increment()
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    inner_increment()
NameError: name 'inner_increment' is not defined
7 nhớ rằng
>>> def increment(number):
...     def inner_increment():
...         return number + 1
...     return inner_increment()
...

>>> increment(10)
11

>>> # Call inner_increment()
>>> inner_increment()
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    inner_increment()
NameError: name 'inner_increment' is not defined
8 và
>>> def increment(number):
...     def inner_increment():
...         return number + 1
...     return inner_increment()
...

>>> increment(10)
11

>>> # Call inner_increment()
>>> inner_increment()
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    inner_increment()
NameError: name 'inner_increment' is not defined
9 nhớ rằng
# hotspots.py

import csv
from collections import Counter

def process_hotspots(file):
    def most_common_provider(file_obj):
        hotspots = []
        with file_obj as csv_file:
            content = csv.DictReader(csv_file)

            for row in content:
                hotspots.append(row["Provider"])

        counter = Counter(hotspots)
        print(
            f"There are {len(hotspots)} Wi-Fi hotspots in NYC.\n"
            f"{counter.most_common(1)[0][0]} has the most with "
            f"{counter.most_common(1)[0][1]}."
        )

    if isinstance(file, str):
        # Got a string-based filepath
        file_obj = open(file, "r")
        most_common_provider(file_obj)
    else:
        # Got a file object
        most_common_provider(file)
0. Lưu ý rằng cả hai đóng cửa đều nhớ
>>> def factorial(number):
...     # Validate input
...     if not isinstance(number, int):
...         raise TypeError("Sorry. 'number' must be an integer.")
...     if number < 0:
...         raise ValueError("Sorry. 'number' must be zero or positive.")
...     # Calculate the factorial of number
...     def inner_factorial(number):
...         if number <= 1:
...             return 1
...         return number * inner_factorial(number - 1)
...     return inner_factorial(number)
...

>>> factorial(4)
24
4 tương ứng giữa các cuộc gọi.

Bây giờ hãy xem xét một ví dụ khác:

Hàm bên trong kiểm tra xem một người dùng nhất định có quyền truy cập chính xác để truy cập một trang nhất định. Bạn có thể nhanh chóng sửa đổi điều này để lấy người dùng trong phiên để kiểm tra xem họ có thông tin đăng nhập chính xác để truy cập một tuyến đường nhất định không.

Thay vì kiểm tra xem người dùng có bằng

# hotspots.py

import csv
from collections import Counter

def process_hotspots(file):
    def most_common_provider(file_obj):
        hotspots = []
        with file_obj as csv_file:
            content = csv.DictReader(csv_file)

            for row in content:
                hotspots.append(row["Provider"])

        counter = Counter(hotspots)
        print(
            f"There are {len(hotspots)} Wi-Fi hotspots in NYC.\n"
            f"{counter.most_common(1)[0][0]} has the most with "
            f"{counter.most_common(1)[0][1]}."
        )

    if isinstance(file, str):
        # Got a string-based filepath
        file_obj = open(file, "r")
        most_common_provider(file_obj)
    else:
        # Got a file object
        most_common_provider(file)
2 hay không, bạn có thể truy vấn cơ sở dữ liệu SQL để kiểm tra quyền và sau đó trả về chế độ xem chính xác tùy thuộc vào việc thông tin đăng nhập có chính xác hay không.Decorators are higher-order functions that take a callable (function, method, class) as an argument and return another callable.

Bạn có thể sử dụng các chức năng trang trí để thêm trách nhiệm vào một cuộc gọi hiện có một cách tự động và mở rộng hành vi của nó một cách minh bạch mà không ảnh hưởng hoặc sửa đổi bản gọi ban đầu có thể gọi được.

Để tạo một trình trang trí, bạn chỉ cần xác định một người có thể gọi (một hàm, phương thức hoặc lớp) chấp nhận một đối tượng hàm là đối số, xử lý nó và trả về một đối tượng chức năng khác với hành vi được thêm vào.

Khi bạn có chức năng trang trí của mình tại chỗ, bạn có thể áp dụng nó cho bất kỳ cuộc gọi nào có thể gọi được. Để làm như vậy, bạn cần sử dụng biểu tượng AT (

>>> from hotspots import process_hotspots

>>> file_obj = open("./NYC_Wi-Fi_Hotspot_Locations.csv", "r")
>>> process_hotspots(file_obj)
There are 3319 Wi-Fi hotspots in NYC.
LinkNYC - Citybridge has the most with 1868.

>>> process_hotspots("./NYC_Wi-Fi_Hotspot_Locations.csv")
There are 3319 Wi-Fi hotspots in NYC.
LinkNYC - Citybridge has the most with 1868.
2) trước tên của người trang trí và sau đó đặt nó lên dòng riêng của nó ngay trước khi có thể gọi được trang trí:

def print_sum(a, b):
    print(sum_numbers(a, b))

print_sum(1, 3)

def sum_numbers(a, b):
    return a + b
4

Cú pháp này làm cho

>>> from hotspots import process_hotspots

>>> file_obj = open("./NYC_Wi-Fi_Hotspot_Locations.csv", "r")
>>> process_hotspots(file_obj)
There are 3319 Wi-Fi hotspots in NYC.
LinkNYC - Citybridge has the most with 1868.

>>> process_hotspots("./NYC_Wi-Fi_Hotspot_Locations.csv")
There are 3319 Wi-Fi hotspots in NYC.
LinkNYC - Citybridge has the most with 1868.
3 tự động lấy
>>> from hotspots import process_hotspots

>>> file_obj = open("./NYC_Wi-Fi_Hotspot_Locations.csv", "r")
>>> process_hotspots(file_obj)
There are 3319 Wi-Fi hotspots in NYC.
LinkNYC - Citybridge has the most with 1868.

>>> process_hotspots("./NYC_Wi-Fi_Hotspot_Locations.csv")
There are 3319 Wi-Fi hotspots in NYC.
LinkNYC - Citybridge has the most with 1868.
4 làm đối số và xử lý nó trong cơ thể của nó. Hoạt động này là một tốc ký cho bài tập sau:

def print_sum(a, b):
    print(sum_numbers(a, b))

print_sum(1, 3)

def sum_numbers(a, b):
    return a + b
5

Dưới đây, một ví dụ về cách xây dựng chức năng trang trí để thêm chức năng mới vào một chức năng hiện có:

>>>

def print_sum(a, b):
    print(sum_numbers(a, b))

print_sum(1, 3)

def sum_numbers(a, b):
    return a + b
6

Trong trường hợp này, bạn sử dụng

>>> from hotspots import process_hotspots

>>> file_obj = open("./NYC_Wi-Fi_Hotspot_Locations.csv", "r")
>>> process_hotspots(file_obj)
There are 3319 Wi-Fi hotspots in NYC.
LinkNYC - Citybridge has the most with 1868.

>>> process_hotspots("./NYC_Wi-Fi_Hotspot_Locations.csv")
There are 3319 Wi-Fi hotspots in NYC.
LinkNYC - Citybridge has the most with 1868.
5 để trang trí
>>> from hotspots import process_hotspots

>>> file_obj = open("./NYC_Wi-Fi_Hotspot_Locations.csv", "r")
>>> process_hotspots(file_obj)
There are 3319 Wi-Fi hotspots in NYC.
LinkNYC - Citybridge has the most with 1868.

>>> process_hotspots("./NYC_Wi-Fi_Hotspot_Locations.csv")
There are 3319 Wi-Fi hotspots in NYC.
LinkNYC - Citybridge has the most with 1868.
6. Điều này thêm chức năng mới cho chức năng được trang trí. Bây giờ khi bạn gọi
>>> from hotspots import process_hotspots

>>> file_obj = open("./NYC_Wi-Fi_Hotspot_Locations.csv", "r")
>>> process_hotspots(file_obj)
There are 3319 Wi-Fi hotspots in NYC.
LinkNYC - Citybridge has the most with 1868.

>>> process_hotspots("./NYC_Wi-Fi_Hotspot_Locations.csv")
There are 3319 Wi-Fi hotspots in NYC.
LinkNYC - Citybridge has the most with 1868.
6, thay vì chỉ in
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-34-37c0e3733861> in <module>()
      2     print(sum_numbers(a, b))
      3 
----> 4 print_sum(1, 3)
      5 
      6 def sum_numbers(a, b):

<ipython-input-34-37c0e3733861> in print_sum(a, b)
      1 def print_sum(a, b):
----> 2     print(sum_numbers(a, b))
      3 
      4 print_sum(1, 3)
      5 

NameError: name 'sum_numbers' is not defined
4, chức năng của bạn in hai tin nhắn mới.

Các trường hợp sử dụng cho trang trí Python rất đa dạng. Dưới đây là một số trong số họ:

  • Gỡ lỗi
  • Bộ nhớ đệm
  • Đăng nhập
  • Thời gian

Một thông lệ phổ biến để gỡ lỗi mã Python là chèn các cuộc gọi vào

>>> from hotspots import process_hotspots

>>> file_obj = open("./NYC_Wi-Fi_Hotspot_Locations.csv", "r")
>>> process_hotspots(file_obj)
There are 3319 Wi-Fi hotspots in NYC.
LinkNYC - Citybridge has the most with 1868.

>>> process_hotspots("./NYC_Wi-Fi_Hotspot_Locations.csv")
There are 3319 Wi-Fi hotspots in NYC.
LinkNYC - Citybridge has the most with 1868.
9 để kiểm tra các giá trị của các biến, để xác nhận rằng một khối mã được thực thi, v.v. Thêm và xóa các cuộc gọi vào
>>> from hotspots import process_hotspots

>>> file_obj = open("./NYC_Wi-Fi_Hotspot_Locations.csv", "r")
>>> process_hotspots(file_obj)
There are 3319 Wi-Fi hotspots in NYC.
LinkNYC - Citybridge has the most with 1868.

>>> process_hotspots("./NYC_Wi-Fi_Hotspot_Locations.csv")
There are 3319 Wi-Fi hotspots in NYC.
LinkNYC - Citybridge has the most with 1868.
9 có thể gây khó chịu và bạn có nguy cơ quên một số trong số chúng. Để ngăn chặn tình huống này, bạn có thể viết một người trang trí như thế này:

>>>

def print_sum(a, b):
    print(sum_numbers(a, b))

print_sum(1, 3)

def sum_numbers(a, b):
    return a + b
7

Trong trường hợp này, bạn sử dụng

>>> from hotspots import process_hotspots

>>> file_obj = open("./NYC_Wi-Fi_Hotspot_Locations.csv", "r")
>>> process_hotspots(file_obj)
There are 3319 Wi-Fi hotspots in NYC.
LinkNYC - Citybridge has the most with 1868.

>>> process_hotspots("./NYC_Wi-Fi_Hotspot_Locations.csv")
There are 3319 Wi-Fi hotspots in NYC.
LinkNYC - Citybridge has the most with 1868.
5 để trang trí
>>> from hotspots import process_hotspots

>>> file_obj = open("./NYC_Wi-Fi_Hotspot_Locations.csv", "r")
>>> process_hotspots(file_obj)
There are 3319 Wi-Fi hotspots in NYC.
LinkNYC - Citybridge has the most with 1868.

>>> process_hotspots("./NYC_Wi-Fi_Hotspot_Locations.csv")
There are 3319 Wi-Fi hotspots in NYC.
LinkNYC - Citybridge has the most with 1868.
6. Điều này thêm chức năng mới cho chức năng được trang trí. Bây giờ khi bạn gọi
>>> from hotspots import process_hotspots

>>> file_obj = open("./NYC_Wi-Fi_Hotspot_Locations.csv", "r")
>>> process_hotspots(file_obj)
There are 3319 Wi-Fi hotspots in NYC.
LinkNYC - Citybridge has the most with 1868.

>>> process_hotspots("./NYC_Wi-Fi_Hotspot_Locations.csv")
There are 3319 Wi-Fi hotspots in NYC.
LinkNYC - Citybridge has the most with 1868.
6, thay vì chỉ in
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-34-37c0e3733861> in <module>()
      2     print(sum_numbers(a, b))
      3 
----> 4 print_sum(1, 3)
      5 
      6 def sum_numbers(a, b):

<ipython-input-34-37c0e3733861> in print_sum(a, b)
      1 def print_sum(a, b):
----> 2     print(sum_numbers(a, b))
      3 
      4 print_sum(1, 3)
      5 

NameError: name 'sum_numbers' is not defined
4, chức năng của bạn in hai tin nhắn mới.

Các trường hợp sử dụng cho trang trí Python rất đa dạng. Dưới đây là một số trong số họ:

>>>

def print_sum(a, b):
    print(sum_numbers(a, b))

print_sum(1, 3)

def sum_numbers(a, b):
    return a + b
8

Trong trường hợp này, bạn sử dụng

>>> from hotspots import process_hotspots

>>> file_obj = open("./NYC_Wi-Fi_Hotspot_Locations.csv", "r")
>>> process_hotspots(file_obj)
There are 3319 Wi-Fi hotspots in NYC.
LinkNYC - Citybridge has the most with 1868.

>>> process_hotspots("./NYC_Wi-Fi_Hotspot_Locations.csv")
There are 3319 Wi-Fi hotspots in NYC.
LinkNYC - Citybridge has the most with 1868.
5 để trang trí
>>> from hotspots import process_hotspots

>>> file_obj = open("./NYC_Wi-Fi_Hotspot_Locations.csv", "r")
>>> process_hotspots(file_obj)
There are 3319 Wi-Fi hotspots in NYC.
LinkNYC - Citybridge has the most with 1868.

>>> process_hotspots("./NYC_Wi-Fi_Hotspot_Locations.csv")
There are 3319 Wi-Fi hotspots in NYC.
LinkNYC - Citybridge has the most with 1868.
6. Điều này thêm chức năng mới cho chức năng được trang trí. Bây giờ khi bạn gọi
>>> from hotspots import process_hotspots

>>> file_obj = open("./NYC_Wi-Fi_Hotspot_Locations.csv", "r")
>>> process_hotspots(file_obj)
There are 3319 Wi-Fi hotspots in NYC.
LinkNYC - Citybridge has the most with 1868.

>>> process_hotspots("./NYC_Wi-Fi_Hotspot_Locations.csv")
There are 3319 Wi-Fi hotspots in NYC.
LinkNYC - Citybridge has the most with 1868.
6, thay vì chỉ in
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-34-37c0e3733861> in <module>()
      2     print(sum_numbers(a, b))
      3 
----> 4 print_sum(1, 3)
      5 
      6 def sum_numbers(a, b):

<ipython-input-34-37c0e3733861> in print_sum(a, b)
      1 def print_sum(a, b):
----> 2     print(sum_numbers(a, b))
      3 
      4 print_sum(1, 3)
      5 

NameError: name 'sum_numbers' is not defined
4, chức năng của bạn in hai tin nhắn mới.

Các trường hợp sử dụng cho trang trí Python rất đa dạng. Dưới đây là một số trong số họ:

Gỡ lỗi

Bộ nhớ đệminner function, also known as a nested function. In Python, inner functions have direct access to the variables and names that you define in the enclosing function. This provides a mechanism for you to create helper functions, closures, and decorators.

Đăng nhập

  • Thời gianencapsulation by nesting functions in other functions
  • Một thông lệ phổ biến để gỡ lỗi mã Python là chèn các cuộc gọi vào
    >>> from hotspots import process_hotspots
    
    >>> file_obj = open("./NYC_Wi-Fi_Hotspot_Locations.csv", "r")
    >>> process_hotspots(file_obj)
    There are 3319 Wi-Fi hotspots in NYC.
    LinkNYC - Citybridge has the most with 1868.
    
    >>> process_hotspots("./NYC_Wi-Fi_Hotspot_Locations.csv")
    There are 3319 Wi-Fi hotspots in NYC.
    LinkNYC - Citybridge has the most with 1868.
    
    9 để kiểm tra các giá trị của các biến, để xác nhận rằng một khối mã được thực thi, v.v. Thêm và xóa các cuộc gọi vào
    >>> from hotspots import process_hotspots
    
    >>> file_obj = open("./NYC_Wi-Fi_Hotspot_Locations.csv", "r")
    >>> process_hotspots(file_obj)
    There are 3319 Wi-Fi hotspots in NYC.
    LinkNYC - Citybridge has the most with 1868.
    
    >>> process_hotspots("./NYC_Wi-Fi_Hotspot_Locations.csv")
    There are 3319 Wi-Fi hotspots in NYC.
    LinkNYC - Citybridge has the most with 1868.
    
    9 có thể gây khó chịu và bạn có nguy cơ quên một số trong số chúng. Để ngăn chặn tình huống này, bạn có thể viết một người trang trí như thế này:helper functions to reuse pieces of code
  • Ví dụ này cung cấp
     1# powers.py
     2
     3def generate_power(exponent):
     4    def power(base):
     5        return base ** exponent
     6    return power
    
    1, là một nhà trang trí có chức năng như một đối số và in chữ ký của nó với giá trị hiện tại của mỗi đối số và giá trị trả về tương ứng của nó. Bạn có thể sử dụng bộ trang trí này để gỡ lỗi các chức năng của bạn. Khi bạn nhận được kết quả mong muốn, bạn có thể loại bỏ người trang trí gọi
     1# powers.py
     2
     3def generate_power(exponent):
     4    def power(base):
     5        return base ** exponent
     6    return power
    
    2 và chức năng của bạn sẽ sẵn sàng cho bước tiếp theo.closure factory functions that retaining state between calls
  • Ở đây, một ví dụ cuối cùng về cách tạo ra một người trang trí. Lần này, bạn sẽ tái tạo lại
    >>> def outer_func(who):
    ...     def inner_func():
    ...         print(f"Hello, {who}")
    ...     inner_func()
    ...
    
    >>> outer_func("World!")
    Hello, World!
    
    8 như một hàm trang trí:decorator functions to provide new functionalities

Phiên bản

>>> def outer_func(who):
...     def inner_func():
...         print(f"Hello, {who}")
...     inner_func()
...

>>> outer_func("World!")
Hello, World!
8 này tạo ra kết quả tương tự bạn có trong triển khai ban đầu. Trong trường hợp này, bạn sử dụng cả đóng cửa để ghi nhớ
>>> def factorial(number):
...     # Validate input
...     if not isinstance(number, int):
...         raise TypeError("Sorry. 'number' must be an integer.")
...     if number < 0:
...         raise ValueError("Sorry. 'number' must be zero or positive.")
...     # Calculate the factorial of number
...     def inner_factorial(number):
...         if number <= 1:
...             return 1
...         return number * inner_factorial(number - 1)
...     return inner_factorial(number)
...

>>> factorial(4)
24
4 và một trình trang trí trả về phiên bản sửa đổi của hàm đầu vào,
 1# powers.py
 2
 3def generate_power(exponent):
 4    def power(base):
 5        return base ** exponent
 6    return power
6.

Ở đây, người trang trí cần phải có một lập luận (

>>> def factorial(number):
...     # Validate input
...     if not isinstance(number, int):
...         raise TypeError("Sorry. 'number' must be an integer.")
...     if number < 0:
...         raise ValueError("Sorry. 'number' must be zero or positive.")
...     # Calculate the factorial of number
...     def inner_factorial(number):
...         if number <= 1:
...             return 1
...         return number * inner_factorial(number - 1)
...     return inner_factorial(number)
...

>>> factorial(4)
24
4), vì vậy bạn cần phải có hai cấp độ chức năng bên trong lồng nhau. Cấp độ đầu tiên được đại diện bởi
>>> def outer_func(who):
...     def inner_func():
...         print(f"Hello, {who}")
...     inner_func()
...

>>> outer_func("World!")
Hello, World!
9, lấy chức năng được trang trí làm đối số. Cấp độ thứ hai được biểu thị bằng
 1# powers.py
 2
 3def generate_power(exponent):
 4    def power(base):
 5        return base ** exponent
 6    return power
9, gói đối số
>>> def factorial(number):
...     # Validate input
...     if not isinstance(number, int):
...         raise TypeError("Sorry. 'number' must be an integer.")
...     if number < 0:
...         raise ValueError("Sorry. 'number' must be zero or positive.")
...     # Calculate the factorial of number
...     def inner_factorial(number):
...         if number <= 1:
...             return 1
...         return number * inner_factorial(number - 1)
...     return inner_factorial(number)
...

>>> factorial(4)
24
4 trong
def print_sum(a, b):
    print(sum_numbers(a, b))

print_sum(1, 3)

def sum_numbers(a, b):
    return a + b
01, đưa ra phép tính cuối cùng của công suất và trả về kết quả. This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Python Inner Functions

Chức năng nên được xác định ở đâu trong Python?

Cú pháp cơ bản Để xác định một hàm trong Python trong Python, bạn xác định một hàm với từ khóa DEF, sau đó viết định danh chức năng (tên) theo sau là dấu ngoặc đơn và dấu hai chấm. Điều tiếp theo bạn phải làm là đảm bảo bạn thụt lề với một tab hoặc 4 khoảng trống, sau đó chỉ định những gì bạn muốn chức năng làm cho bạn.define a function with the def keyword, then write the function identifier (name) followed by parentheses and a colon. The next thing you have to do is make sure you indent with a tab or 4 spaces, and then specify what you want the function to do for you.

Bạn có thể xác định các chức năng ở bất cứ đâu trong Python không?

Bất cứ nơi nào trong ứng dụng của bạn mà bạn cần hoàn thành nhiệm vụ, bạn chỉ cần gọi chức năng.Xuống dòng, nếu bạn quyết định thay đổi cách thức hoạt động, thì bạn chỉ cần thay đổi mã ở một vị trí, đó là nơi xác định hàm.you simply call the function. Down the line, if you decide to change how it works, then you only need to change the code in one location, which is the place where the function is defined.

Thứ tự chức năng có quan trọng Python không?

Không quan trọng chúng được đưa ra theo thứ tự nào trong tham số miễn là các đối số trong biểu thức cuộc gọi phù hợp với biến chính xác.Dù bằng cách nào sẽ không quan trọng với chuỗi đầu ra.. Either way won't matter to the output string.

Nên chức năng chính ở trên cùng hoặc dưới cùng?

Công ước thông thường là đặt chúng ở cuối kịch bản.Và tất nhiên bạn không thể gọi chính trước khi xác định nó.at the end of the script. And of course you can't call main before you define it.