Hướng dẫn python function inside function variable scope - chức năng python bên trong phạm vi biến chức năng

>>> def get_order_total[quantity]:
    global PRICE_RANGES

    total = 0
    _i = PRICE_RANGES.iterkeys[]
    def recurse[_i]:
    print locals[]
    print globals[]
        try:
            key = _i.next[]
            if quantity % key != quantity:
                total += PRICE_RANGES[key][0]
            return recurse[_i]
        except StopIteration:
            return [key, quantity % key]
    print 'main function', locals[], globals[]

    res = recurse[_i]


>>> get_order_total[20]
main function {'total': 0, 'recurse': , '_i': , 'quantity': 20} {'__builtins__': , 'PRICE_RANGES': {64: [25, 0.34999999999999998], 32: [13, 0.40000000000000002], 16: [7, 0.45000000000000001], 8: [4, 0.5]}, '__package__': None, 's': , 'get_order_total': , '__name__': '__main__', '__doc__': None}
{'recurse': , '_i': , 'quantity': 20}
{'__builtins__': , 'PRICE_RANGES': {64: [25, 0.34999999999999998], 32: [13, 0.40000000000000002], 16: [7, 0.45000000000000001], 8: [4, 0.5]}, '__package__': None, 's': , 'get_order_total': , '__name__': '__main__', '__doc__': None}
{'recurse': , '_i': , 'quantity': 20}
{'__builtins__': , 'PRICE_RANGES': {64: [25, 0.34999999999999998], 32: [13, 0.40000000000000002], 16: [7, 0.45000000000000001], 8: [4, 0.5]}, '__package__': None, 's': , 'get_order_total': , '__name__': '__main__', '__doc__': None}
{'recurse': , '_i': , 'quantity': 20}
{'__builtins__': , 'PRICE_RANGES': {64: [25, 0.34999999999999998], 32: [13, 0.40000000000000002], 16: [7, 0.45000000000000001], 8: [4, 0.5]}, '__package__': None, 's': , 'get_order_total': , '__name__': '__main__', '__doc__': None}

Traceback [most recent call last]:
  File "", line 1, in 
    get_order_total[20]
  File "", line 18, in get_order_total
    res = recurse[_i]
  File "", line 13, in recurse
    return recurse[_i]
  File "", line 13, in recurse
    return recurse[_i]
  File "", line 12, in recurse
    total += PRICE_RANGES[key][0]
UnboundLocalError: local variable 'total' referenced before assignment
>>> 

Như bạn thấy, Total nằm trong phạm vi cục bộ của chức năng chính, nhưng nó không nằm trong phạm vi tái diễn cục bộ [rõ ràng] nhưng nó cũng không nằm trong phạm vi toàn cầu

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úng ta có thể gọi một hàm bên trong một hàm trong Python không?, 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.

Trong Python, bất kỳ chức năng bằng văn bản nào cũng có thể được gọi bởi một hàm khác. Lưu ý rằng đây có thể là cách phá vỡ một vấn đề thanh lịch nhất thành các vấn đề nhỏ.

  • Chức năng biến Python có phạm vi không?encapsulation and hide your functions from external access
  • Một biến được tạo bên trong một hàm thuộc phạm vi cục bộ của hàm đó và chỉ có thể được sử dụng bên trong hàm đó.helper functions to facilitate code reuse
  • Phạm vi của một hàm lồng nhau là gì?closure factory functions that retain state between calls
  • Phạm vi của hàm lồng nhau nằm trong hàm bao quanh, tức là bên trong một trong các khối cấu thành của hàm đó, điều đó có nghĩa là nó vô hình bên ngoài khối đó và cả bên ngoài hàm bao quanh. Một hàm lồng nhau có thể truy cập các hàm, biến, hằng số, loại, lớp, v.v.decorator functions to add behavior to existing functions

Tôi có thể truy cập biến bên trong chức năng Python không?

Bạn có thể truy cập các biến như vậy bên trong và bên ngoài một hàm, vì chúng có phạm vi toàn cầu.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:

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í.

>>> def outer_func[]:
...     def inner_func[]:
...         print["Hello, World!"]
...     inner_func[]
...

>>> outer_func[]
Hello, World!

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

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

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í.

>>> def outer_func[who]:
...     def inner_func[]:
...         print[f"Hello, {who}"]
...     inner_func[]
...

>>> outer_func["World!"]
Hello, World!

Trong hướng dẫn này, bạn sẽ học cách:nonlocal names. They are nonlocal from the

>>> def outer_func[]:
...     def inner_func[]:
...         print["Hello, World!"]
...     inner_func[]
...

>>> outer_func[]
Hello, World!
7 point of view.

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

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í.

>>> def factorial[number]:
...     # Validate input
...     if not isinstance[number, int]:
...         raise TypeError["Sorry. 'number' must be an integer."]
...     if number > factorial[4]
24

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

Ư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 "", line 1, in 
    inner_increment[]
NameError: name 'inner_increment' is not defined

Trong ví dụ này, bạn có thể truy cập trực tiếp vào

>>> def factorial[number]:
...     # Validate input
...     if not isinstance[number, int]:
...         raise TypeError["Sorry. 'number' must be an integer."]
...     if number > factorial[4]
24
0. Nếu bạn cố gắng làm điều đó, thì bạn sẽ nhận được
>>> def factorial[number]:
...     # Validate input
...     if not isinstance[number, int]:
...         raise TypeError["Sorry. 'number' must be an integer."]
...     if number > factorial[4]
24
1. Điều đó vì
>>> def factorial[number]:
...     # Validate input
...     if not isinstance[number, int]:
...         raise TypeError["Sorry. 'number' must be an integer."]
...     if number > factorial[4]
24
2 hoàn toàn ẩn
>>> def factorial[number]:
...     # Validate input
...     if not isinstance[number, int]:
...         raise TypeError["Sorry. 'number' must be an integer."]
...     if number > factorial[4]
24
0, 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

Đô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:

# 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]

Ở đây,

>>> def factorial[number]:
...     # Validate input
...     if not isinstance[number, int]:
...         raise TypeError["Sorry. 'number' must be an integer."]
...     if number > factorial[4]
24
4 lấy
>>> def factorial[number]:
...     # Validate input
...     if not isinstance[number, int]:
...         raise TypeError["Sorry. 'number' must be an integer."]
...     if number > factorial[4]
24
5 làm đối số. Hàm kiểm tra xem
>>> def factorial[number]:
...     # Validate input
...     if not isinstance[number, int]:
...         raise TypeError["Sorry. 'number' must be an integer."]
...     if number > factorial[4]
24
5 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 factorial[number]:
...     # Validate input
...     if not isinstance[number, int]:
...         raise TypeError["Sorry. 'number' must be an integer."]
...     if number > factorial[4]
24
7, lấy một đối tượng tệp và thực hiện các hoạt động sau:

  1. Đọ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 factorial[number]:
    ...     # Validate input
    ...     if not isinstance[number, int]:
    ...         raise TypeError["Sorry. 'number' must be an integer."]
    ...     if number > factorial[4]
    24
    
    8.
  2. Tạo một danh sách các nhà cung cấp Wi-Fi.
  3. Đếm số lượng điểm nóng Wi-Fi trên mỗi nhà cung cấp bằng đối tượng
    >>> def factorial[number]:
    ...     # Validate input
    ...     if not isinstance[number, int]:
    ...         raise TypeError["Sorry. 'number' must be an integer."]
    ...     if number > factorial[4]
    24
    
    9.
  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:

>>>

>>> 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.

Trong ví dụ này, bạn có thể truy cập trực tiếp vào

>>> def factorial[number]:
...     # Validate input
...     if not isinstance[number, int]:
...         raise TypeError["Sorry. 'number' must be an integer."]
...     if number > factorial[4]
24
0. Nếu bạn cố gắng làm điều đó, thì bạn sẽ nhận được
>>> def factorial[number]:
...     # Validate input
...     if not isinstance[number, int]:
...         raise TypeError["Sorry. 'number' must be an integer."]
...     if number > factorial[4]
24
1. Điều đó vì
>>> def factorial[number]:
...     # Validate input
...     if not isinstance[number, int]:
...         raise TypeError["Sorry. 'number' must be an integer."]
...     if number > factorial[4]
24
2 hoàn toàn ẩn
>>> def factorial[number]:
...     # Validate input
...     if not isinstance[number, int]:
...         raise TypeError["Sorry. 'number' must be an integer."]
...     if number > factorial[4]
24
0, 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

Đô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 factorial[number]:
...     # Validate input
...     if not isinstance[number, int]:
...         raise TypeError["Sorry. 'number' must be an integer."]
...     if number > factorial[4]
24
4 lấy
>>> def factorial[number]:
...     # Validate input
...     if not isinstance[number, int]:
...         raise TypeError["Sorry. 'number' must be an integer."]
...     if number > factorial[4]
24
5 làm đối số. Hàm kiểm tra xem
>>> def factorial[number]:
...     # Validate input
...     if not isinstance[number, int]:
...         raise TypeError["Sorry. 'number' must be an integer."]
...     if number > factorial[4]
24
5 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 factorial[number]:
...     # Validate input
...     if not isinstance[number, int]:
...         raise TypeError["Sorry. 'number' must be an integer."]
...     if number > factorial[4]
24
7, 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 factorial[number]:
...     # Validate input
...     if not isinstance[number, int]:
...         raise TypeError["Sorry. 'number' must be an integer."]
...     if number > factorial[4]
24
8.

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 factorial[number]:
...     # Validate input
...     if not isinstance[number, int]:
...         raise TypeError["Sorry. 'number' must be an integer."]
...     if number > factorial[4]
24
9.

In một tin nhắn với thông tin được truy xuất.Higher-order functions are functions that operate on other functions by taking them as arguments, returning them, or both.

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 factorial[number]:
...     # Validate input
...     if not isinstance[number, int]:
...         raise TypeError["Sorry. 'number' must be an integer."]
...     if number > factorial[4]
24
4 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ự.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.

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

  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 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 "", line 1, in 
        inner_increment[]
    NameError: name 'inner_increment' is not defined
    
    3, 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 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 "", line 1, in 
        inner_increment[]
    NameError: name 'inner_increment' is not defined
    
    3, 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 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 "", line 1, in 
        inner_increment[]
    NameError: name 'inner_increment' is not defined
    
    4, là hàm bên trong có một đối số duy nhất,
    >>> 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 "", line 1, in 
        inner_increment[]
    NameError: name 'inner_increment' is not defined
    
    5 và trả về kết quả của biểu thức
    >>> 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 "", line 1, in 
        inner_increment[]
    NameError: name 'inner_increment' is not defined
    
    6.
    defines
    >>> 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 "", line 1, in 
        inner_increment[]
    NameError: name 'inner_increment' is not defined
    
    4, which is an inner function that takes a single argument,
    >>> 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 "", line 1, in 
        inner_increment[]
    NameError: name 'inner_increment' is not defined
    
    5, and returns the result of the expression
    >>> 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 "", line 1, in 
        inner_increment[]
    NameError: name 'inner_increment' is not defined
    
    6.
  • Dòng 6 trả 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 "", line 1, in 
        inner_increment[]
    NameError: name 'inner_increment' is not defined
    
    7 dưới dạng đối tượng hàm, mà không gọi nó.
    returns
    >>> 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 "", line 1, in 
        inner_increment[]
    NameError: name 'inner_increment' is not defined
    
    7 as a function object, without calling it.

>>> 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 "", line 1, in 
    inner_increment[]
NameError: name 'inner_increment' is not defined
4 nhận được giá trị của
>>> 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 "", line 1, in 
    inner_increment[]
NameError: name 'inner_increment' is not defined
9 từ đâu? Đây là nơi đóng cửa đi vào chơi. Trong 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 "", line 1, in 
    inner_increment[]
NameError: name 'inner_increment' is not defined
4 nhận được giá trị của
>>> 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 "", line 1, in 
    inner_increment[]
NameError: name 'inner_increment' is not defined
9 từ hàm bên ngoài,
>>> 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 "", line 1, in 
    inner_increment[]
NameError: name 'inner_increment' is not defined
3. Ở đây, những gì Python làm khi bạn gọi
>>> 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 "", line 1, in 
    inner_increment[]
NameError: name 'inner_increment' is not defined
3:

  1. Xác định một thể hiện mới của
    >>> 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 "", line 1, in 
        inner_increment[]
    NameError: name 'inner_increment' is not defined
    
    4, có một đối số duy nhất
    >>> 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 "", line 1, in 
        inner_increment[]
    NameError: name 'inner_increment' is not defined
    
    5.
  2. Chụp ảnh chụp nhanh về trạng thái xung quanh
    >>> 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 "", line 1, in 
        inner_increment[]
    NameError: name 'inner_increment' is not defined
    
    4, bao gồ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 "", line 1, in 
        inner_increment[]
    NameError: name 'inner_increment' is not defined
    
    9 với giá trị hiện tại của nó.
  3. Trả lại
    >>> 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 "", line 1, in 
        inner_increment[]
    NameError: name 'inner_increment' is not defined
    
    4 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 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 "", line 1, in 
    inner_increment[]
NameError: name 'inner_increment' is not defined
4 được trả về bởi
>>> 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 "", line 1, in 
    inner_increment[]
NameError: name 'inner_increment' is not defined
3, bạn sẽ thấy rằng hàm này nhớ lại giá trị của
>>> 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 "", line 1, in 
    inner_increment[]
NameError: name 'inner_increment' is not defined
9:

>>>

>>> from powers import generate_power

>>> raise_two = generate_power[2]
>>> raise_three = generate_power[3]

>>> raise_two[4]
16
>>> raise_two[5]
25

>>> raise_three[4]
64
>>> raise_three[5]
125

Trong các ví dụ nà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.
2 nhớ rằ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.
3 và
>>> 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 nhớ rằ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. Lưu ý rằng cả hai đóng cửa đều nhớ
>>> 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 "", line 1, in 
    inner_increment[]
NameError: name 'inner_increment' is not defined
9 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 has_permission[page]:
...     def permission[username]:
...         if username.lower[] == "admin":
...             return f"'{username}' has access to {page}."
...         else:
...             return f"'{username}' doesn't have access to {page}."
...     return permission
...

>>> check_admin_page_permision = has_permission["Admin Page"]

>>> check_admin_page_permision["admin"]
"'admin' has access to Admin Page."

>>> check_admin_page_permision["john"]
"'john' doesn't have access to Admin Page."

Trong các ví dụ nà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.
2 nhớ rằ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.
3 và
>>> 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 nhớ rằ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. Lưu ý rằng cả hai đóng cửa đều nhớ
>>> 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 "", line 1, in 
    inner_increment[]
NameError: name 'inner_increment' is not defined
9 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

>>> 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.
7 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,
>>> 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 nhớ rằ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.
3 và
>>> 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 nhớ rằ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. Lưu ý rằng cả hai đóng cửa đều nhớ
>>> 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 "", line 1, in 
    inner_increment[]
NameError: name 'inner_increment' is not defined
9 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

>>> 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.
7 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 outer_func[]:
...     def inner_func[]:
...         print["Hello, World!"]
...     inner_func[]
...

>>> outer_func[]
Hello, World!
1

Trong các ví dụ nà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.
2 nhớ rằ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.
3 và
>>> 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 nhớ rằ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. Lưu ý rằng cả hai đóng cửa đều nhớ
>>> 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 "", line 1, in 
    inner_increment[]
NameError: name 'inner_increment' is not defined
9 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

>>> 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.
7 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 thường tạo ra các đóng cửa mà don không thể sửa đổi trạng thái bao quanh của chúng hoặc đóng cửa với trạng thái bao quanh tĩnh, như bạn đã thấy trong các ví dụ trên. Tuy nhiên, bạn cũng có thể tạo các đóng cửa sửa đổi trạng thái kèm theo của chúng bằng cách sử dụng các đối tượng có thể thay đổi, chẳng hạn như từ điển, bộ hoặc danh sách.

Giả sử bạn cần tính giá trị trung bình của bộ dữ liệu. Dữ liệu đi kèm trong một luồng các phép đo liên tiếp của tham số được phân tích và bạn cần chức năng của mình để giữ lại các phép đo trước đó giữa các cuộc gọi. Trong trường hợp này, bạn có thể mã hóa chức năng đóng cửa của nhà máy như thế này:

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 [____777] 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 outer_func[]:
...     def inner_func[]:
...         print["Hello, World!"]
...     inner_func[]
...

>>> outer_func[]
Hello, World!
2

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

 1# powers.py
 2
 3def generate_power[exponent]:
 4    def power[base]:
 5        return base ** exponent
 6    return power
8 tự động lấy
 1# powers.py
 2
 3def generate_power[exponent]:
 4    def power[base]:
 5        return base ** exponent
 6    return power
9 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 outer_func[]:
...     def inner_func[]:
...         print["Hello, World!"]
...     inner_func[]
...

>>> outer_func[]
Hello, World!
3

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 outer_func[]:
...     def inner_func[]:
...         print["Hello, World!"]
...     inner_func[]
...

>>> outer_func[]
Hello, World!
4

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

>>> from powers import generate_power

>>> raise_two = generate_power[2]
>>> raise_three = generate_power[3]

>>> raise_two[4]
16
>>> raise_two[5]
25

>>> raise_three[4]
64
>>> raise_three[5]
125
0 để trang trí
>>> from powers import generate_power

>>> raise_two = generate_power[2]
>>> raise_three = generate_power[3]

>>> raise_two[4]
16
>>> raise_two[5]
25

>>> raise_three[4]
64
>>> raise_three[5]
125
1. Đ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 powers import generate_power

>>> raise_two = generate_power[2]
>>> raise_three = generate_power[3]

>>> raise_two[4]
16
>>> raise_two[5]
25

>>> raise_three[4]
64
>>> raise_three[5]
125
1, thay vì chỉ in
>>> def outer_func[]:
...     def inner_func[]:
...         print["Hello, World!"]
...     inner_func[]
...

>>> outer_func[]
Hello, World!
9, 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 powers import generate_power

>>> raise_two = generate_power[2]
>>> raise_three = generate_power[3]

>>> raise_two[4]
16
>>> raise_two[5]
25

>>> raise_three[4]
64
>>> raise_three[5]
125
4 để 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 powers import generate_power

>>> raise_two = generate_power[2]
>>> raise_three = generate_power[3]

>>> raise_two[4]
16
>>> raise_two[5]
25

>>> raise_three[4]
64
>>> raise_three[5]
125
4 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 outer_func[]:
...     def inner_func[]:
...         print["Hello, World!"]
...     inner_func[]
...

>>> outer_func[]
Hello, World!
5

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

>>> from powers import generate_power

>>> raise_two = generate_power[2]
>>> raise_three = generate_power[3]

>>> raise_two[4]
16
>>> raise_two[5]
25

>>> raise_three[4]
64
>>> raise_three[5]
125
0 để trang trí
>>> from powers import generate_power

>>> raise_two = generate_power[2]
>>> raise_three = generate_power[3]

>>> raise_two[4]
16
>>> raise_two[5]
25

>>> raise_three[4]
64
>>> raise_three[5]
125
1. Đ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 powers import generate_power

>>> raise_two = generate_power[2]
>>> raise_three = generate_power[3]

>>> raise_two[4]
16
>>> raise_two[5]
25

>>> raise_three[4]
64
>>> raise_three[5]
125
1, thay vì chỉ in
>>> def outer_func[]:
...     def inner_func[]:
...         print["Hello, World!"]
...     inner_func[]
...

>>> outer_func[]
Hello, World!
9, 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 outer_func[]:
...     def inner_func[]:
...         print["Hello, World!"]
...     inner_func[]
...

>>> outer_func[]
Hello, World!
6

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

>>> from powers import generate_power

>>> raise_two = generate_power[2]
>>> raise_three = generate_power[3]

>>> raise_two[4]
16
>>> raise_two[5]
25

>>> raise_three[4]
64
>>> raise_three[5]
125
0 để trang trí
>>> from powers import generate_power

>>> raise_two = generate_power[2]
>>> raise_three = generate_power[3]

>>> raise_two[4]
16
>>> raise_two[5]
25

>>> raise_three[4]
64
>>> raise_three[5]
125
1. Đ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 powers import generate_power

>>> raise_two = generate_power[2]
>>> raise_three = generate_power[3]

>>> raise_two[4]
16
>>> raise_two[5]
25

>>> raise_three[4]
64
>>> raise_three[5]
125
1, thay vì chỉ in
>>> def outer_func[]:
...     def inner_func[]:
...         print["Hello, World!"]
...     inner_func[]
...

>>> outer_func[]
Hello, World!
9, 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 powers import generate_power
    
    >>> raise_two = generate_power[2]
    >>> raise_three = generate_power[3]
    
    >>> raise_two[4]
    16
    >>> raise_two[5]
    25
    
    >>> raise_three[4]
    64
    >>> raise_three[5]
    125
    
    4 để 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 powers import generate_power
    
    >>> raise_two = generate_power[2]
    >>> raise_three = generate_power[3]
    
    >>> raise_two[4]
    16
    >>> raise_two[5]
    25
    
    >>> raise_three[4]
    64
    >>> raise_three[5]
    125
    
    4 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
    >>> from powers import generate_power
    
    >>> raise_two = generate_power[2]
    >>> raise_three = generate_power[3]
    
    >>> raise_two[4]
    16
    >>> raise_two[5]
    25
    
    >>> raise_three[4]
    64
    >>> raise_three[5]
    125
    
    6, 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
    >>> from powers import generate_power
    
    >>> raise_two = generate_power[2]
    >>> raise_three = generate_power[3]
    
    >>> raise_two[4]
    16
    >>> raise_two[5]
    25
    
    >>> raise_three[4]
    64
    >>> raise_three[5]
    125
    
    7 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 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 "", line 1, in 
        inner_increment[]
    NameError: name 'inner_increment' is not defined
    
    3 như một hàm trang trí:decorator functions to provide new functionalities

Phiên bản

>>> 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 "", line 1, in 
    inner_increment[]
NameError: name 'inner_increment' is not defined
3 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 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 "", line 1, in 
    inner_increment[]
NameError: name 'inner_increment' is not defined
9 và một trình trang trí trả về phiên bản sửa đổi của hàm đầu vào,
>>> def has_permission[page]:
...     def permission[username]:
...         if username.lower[] == "admin":
...             return f"'{username}' has access to {page}."
...         else:
...             return f"'{username}' doesn't have access to {page}."
...     return permission
...

>>> check_admin_page_permision = has_permission["Admin Page"]

>>> check_admin_page_permision["admin"]
"'admin' has access to Admin Page."

>>> check_admin_page_permision["john"]
"'john' doesn't have access to Admin Page."
1.

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

>>> 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 "", line 1, in 
    inner_increment[]
NameError: name 'inner_increment' is not defined
9], 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 thể hiện bởi
>>> 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 "", line 1, in 
    inner_increment[]
NameError: name 'inner_increment' is not defined
4, lấy chức năng được trang trí làm đối số. Cấp độ thứ hai được biểu thị bằng
>>> def has_permission[page]:
...     def permission[username]:
...         if username.lower[] == "admin":
...             return f"'{username}' has access to {page}."
...         else:
...             return f"'{username}' doesn't have access to {page}."
...     return permission
...

>>> check_admin_page_permision = has_permission["Admin Page"]

>>> check_admin_page_permision["admin"]
"'admin' has access to Admin Page."

>>> check_admin_page_permision["john"]
"'john' doesn't have access to Admin Page."
4, đóng gói đối số
>>> 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 "", line 1, in 
    inner_increment[]
NameError: name 'inner_increment' is not defined
9 trong
>>> def has_permission[page]:
...     def permission[username]:
...         if username.lower[] == "admin":
...             return f"'{username}' has access to {page}."
...         else:
...             return f"'{username}' doesn't have access to {page}."
...     return permission
...

>>> check_admin_page_permision = has_permission["Admin Page"]

>>> check_admin_page_permision["admin"]
"'admin' has access to Admin Page."

>>> check_admin_page_permision["john"]
"'john' doesn't have access to Admin Page."
6, thực hiện tính toán 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úng ta có thể gọi một hàm bên trong một hàm trong Python không?

Trong Python, bất kỳ chức năng bằng văn bản nào cũng có thể được gọi bởi một hàm khác.Lưu ý rằng đây có thể là cách phá vỡ một vấn đề thanh lịch nhất thành các vấn đề nhỏ.any written function can be called by another function. Note that this could be the most elegant way of breaking a problem into chunks of small problems.

Chức năng biến Python có phạm vi không?

Một biến được tạo bên trong một hàm thuộc phạm vi cục bộ của hàm đó và chỉ có thể được sử dụng bên trong hàm đó., and can only be used inside that function.

Phạm vi của một hàm lồng nhau là gì?

Phạm vi của hàm lồng nhau nằm trong hàm bao quanh, tức là bên trong một trong các khối cấu thành của hàm đó, điều đó có nghĩa là nó vô hình bên ngoài khối đó và cả bên ngoài hàm bao quanh.Một hàm lồng nhau có thể truy cập các hàm, biến, hằng số, loại, lớp, v.v.inside the enclosing function, i.e. inside one of the constituent blocks of that function, which means that it is invisible outside that block and also outside the enclosing function. A nested function can access other local functions, variables, constants, types, classes, etc.

Tôi có thể truy cập biến bên trong chức năng Python không?

Bạn có thể truy cập các biến như vậy bên trong và bên ngoài một hàm, vì chúng có phạm vi toàn cầu., as they have global scope.

Bài Viết Liên Quan

Chủ Đề