Hướng dẫn python functools flatmap - bản đồ phẳng của trăn functools

Mã nguồn: lib/functools.py Lib/functools.py


Mô-đun

class DataSet:
    def __init__(self, sequence_of_numbers):
        self._data = sequence_of_numbers

    @property
    @cache
    def stdev(self):
        return statistics.stdev(self._data)
5 dành cho các hàm bậc cao hơn: các chức năng hoạt động hoặc trả về các chức năng khác. Nói chung, bất kỳ đối tượng có thể gọi nào cũng có thể được coi là một hàm cho các mục đích của mô -đun này.

Mô -đun

class DataSet:
    def __init__(self, sequence_of_numbers):
        self._data = sequence_of_numbers

    @property
    @cache
    def stdev(self):
        return statistics.stdev(self._data)
5 xác định các chức năng sau:

@functools.cache (user_function) ¶functools.cache(user_function)

Đơn giản nhẹ hơn Bộ đệm chức năng không giới hạn. Đôi khi được gọi là bản ghi nhớ của người Viking.

Trả về giống như

class DataSet:
    def __init__(self, sequence_of_numbers):
        self._data = sequence_of_numbers

    @property
    @cache
    def stdev(self):
        return statistics.stdev(self._data)
7, tạo ra một trình bao bọc mỏng xung quanh việc tìm kiếm từ điển cho các đối số chức năng. Bởi vì nó không bao giờ cần phải trục xuất các giá trị cũ, điều này nhỏ hơn và nhanh hơn
class DataSet:
    def __init__(self, sequence_of_numbers):
        self._data = sequence_of_numbers

    @property
    @cache
    def stdev(self):
        return statistics.stdev(self._data)
8 với giới hạn kích thước.

Ví dụ:

@cache
def factorial(n):
    return n * factorial(n-1) if n else 1

>>> factorial(10)      # no previously cached result, makes 11 recursive calls
3628800
>>> factorial(5)       # just looks up cached value result
120
>>> factorial(12)      # makes two new recursive calls, the other 10 are cached
479001600

Mới trong phiên bản 3.9.

@functools.cached_property (func) ¶functools.cached_property(func)

Chuyển đổi một phương thức của một lớp thành một thuộc tính có giá trị được tính một lần và sau đó được lưu trong bộ nhớ cache như một thuộc tính bình thường cho tuổi thọ của trường hợp. Tương tự như

class DataSet:
    def __init__(self, sequence_of_numbers):
        self._data = sequence_of_numbers

    @property
    @cache
    def stdev(self):
        return statistics.stdev(self._data)
9, với việc bổ sung bộ nhớ đệm. Hữu ích cho các thuộc tính tính toán đắt tiền của các trường hợp có hiệu quả khác.

Example:

class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)

Các cơ chế của

sorted(iterable, key=cmp_to_key(locale.strcoll))  # locale-aware sort order
0 có phần khác với
class DataSet:
    def __init__(self, sequence_of_numbers):
        self._data = sequence_of_numbers

    @property
    @cache
    def stdev(self):
        return statistics.stdev(self._data)
9. Một thuộc tính thông thường chặn thuộc tính ghi trừ khi một setter được xác định. Ngược lại, một bộ nhớ cache_property cho phép viết.

Bộ trang trí bộ nhớ cache_property chỉ chạy trên các tra cứu và chỉ khi một thuộc tính cùng tên không tồn tại. Khi nó chạy, bộ nhớ cache_property ghi vào thuộc tính có cùng tên. Thuộc tính tiếp theo đọc và ghi được ưu tiên hơn phương thức lưu trữ_property và nó hoạt động giống như một thuộc tính thông thường.

Giá trị được lưu trong bộ nhớ cache có thể được xóa bằng cách xóa thuộc tính. Điều này cho phép phương thức lưu trữ_property chạy lại.

Lưu ý, người trang trí này can thiệp vào hoạt động của từ điển chia sẻ khóa PEP 412. Điều này có nghĩa là từ điển thể hiện có thể chiếm nhiều không gian hơn bình thường.PEP 412 key-sharing dictionaries. This means that instance dictionaries can take more space than usual.

Ngoài ra, bộ trang trí này yêu cầu thuộc tính

sorted(iterable, key=cmp_to_key(locale.strcoll))  # locale-aware sort order
2 trên mỗi trường hợp là một ánh xạ có thể thay đổi. Điều này có nghĩa là nó sẽ không hoạt động với một số loại, chẳng hạn như các metaclass (vì các thuộc tính
sorted(iterable, key=cmp_to_key(locale.strcoll))  # locale-aware sort order
2 trên các phiên bản loại chỉ là proxy chỉ đọc cho không gian tên lớp) và các thuộc tính chỉ định
sorted(iterable, key=cmp_to_key(locale.strcoll))  # locale-aware sort order
4 mà không bao gồm không cung cấp thuộc tính
sorted(iterable, key=cmp_to_key(locale.strcoll))  # locale-aware sort order
2 ở tất cả).

Nếu không có bản đồ có thể thay đổi hoặc nếu mong muốn chia sẻ khóa tiết kiệm không gian, có thể đạt được hiệu ứng tương tự như

sorted(iterable, key=cmp_to_key(locale.strcoll))  # locale-aware sort order
0 bằng cách xếp chồng
class DataSet:
    def __init__(self, sequence_of_numbers):
        self._data = sequence_of_numbers

    @property
    @cache
    def stdev(self):
        return statistics.stdev(self._data)
9 trên đầu
sorted(iterable, key=cmp_to_key(locale.strcoll))  # locale-aware sort order
9:

class DataSet:
    def __init__(self, sequence_of_numbers):
        self._data = sequence_of_numbers

    @property
    @cache
    def stdev(self):
        return statistics.stdev(self._data)

Mới trong phiên bản 3.8.

functools.cmp_to_key (func) ¶cmp_to_key(func)

Chuyển đổi một hàm so sánh kiểu cũ thành một hàm chính. Được sử dụng với các công cụ chấp nhận các chức năng chính (chẳng hạn như

@lru_cache
def count_vowels(sentence):
    return sum(sentence.count(vowel) for vowel in 'AEIOUaeiou')
0,
@lru_cache
def count_vowels(sentence):
    return sum(sentence.count(vowel) for vowel in 'AEIOUaeiou')
1,
@lru_cache
def count_vowels(sentence):
    return sum(sentence.count(vowel) for vowel in 'AEIOUaeiou')
2,
@lru_cache
def count_vowels(sentence):
    return sum(sentence.count(vowel) for vowel in 'AEIOUaeiou')
3,
@lru_cache
def count_vowels(sentence):
    return sum(sentence.count(vowel) for vowel in 'AEIOUaeiou')
4,
@lru_cache
def count_vowels(sentence):
    return sum(sentence.count(vowel) for vowel in 'AEIOUaeiou')
5). Chức năng này chủ yếu được sử dụng như một công cụ chuyển tiếp cho các chương trình được chuyển đổi từ Python 2, hỗ trợ việc sử dụng các hàm so sánh.key function. Used with tools that accept key functions (such as
@lru_cache
def count_vowels(sentence):
    return sum(sentence.count(vowel) for vowel in 'AEIOUaeiou')
0,
@lru_cache
def count_vowels(sentence):
    return sum(sentence.count(vowel) for vowel in 'AEIOUaeiou')
1,
@lru_cache
def count_vowels(sentence):
    return sum(sentence.count(vowel) for vowel in 'AEIOUaeiou')
2,
@lru_cache
def count_vowels(sentence):
    return sum(sentence.count(vowel) for vowel in 'AEIOUaeiou')
3,
@lru_cache
def count_vowels(sentence):
    return sum(sentence.count(vowel) for vowel in 'AEIOUaeiou')
4,
@lru_cache
def count_vowels(sentence):
    return sum(sentence.count(vowel) for vowel in 'AEIOUaeiou')
5). This function is primarily used as a transition tool for programs being converted from Python 2 which supported the use of comparison functions.

Một hàm so sánh là bất kỳ chức năng nào có thể gọi được chấp nhận hai đối số, so sánh chúng và trả về một số âm cho ít hơn, không cho sự bình đẳng hoặc số dương cho lớn hơn. Chức năng khóa là có thể gọi được chấp nhận một đối số và trả về một giá trị khác được sử dụng làm phím sắp xếp.

Example:

sorted(iterable, key=cmp_to_key(locale.strcoll))  # locale-aware sort order

Để sắp xếp các ví dụ và một hướng dẫn sắp xếp ngắn gọn, xem phân loại cách.Sorting HOW TO.

Mới trong phiên bản 3.2.

@functools.lru_cache (user_function)functools.lru_cache(user_function)@functools.lru_cache(maxsize=128, typed=False)

Người trang trí để bọc một chức năng với một bản ghi nhớ có thể gọi được để tiết kiệm tối đa các cuộc gọi gần đây nhất. Nó có thể tiết kiệm thời gian khi một hàm ràng buộc I/O đắt tiền được gọi định kỳ với cùng một đối số.

Vì một từ điển được sử dụng để lưu trữ kết quả, nên các đối số từ khóa và từ khóa đối với hàm phải được băm.

Các mẫu đối số riêng biệt có thể được coi là các cuộc gọi riêng biệt với các mục bộ đệm riêng biệt. Ví dụ:

@lru_cache
def count_vowels(sentence):
    return sum(sentence.count(vowel) for vowel in 'AEIOUaeiou')
6 và
@lru_cache
def count_vowels(sentence):
    return sum(sentence.count(vowel) for vowel in 'AEIOUaeiou')
7 khác nhau trong thứ tự đối số từ khóa của họ và có thể có hai mục bộ đệm riêng biệt.

Nếu user_function được chỉ định, nó phải có thể gọi được. Điều này cho phép trình trang trí LRU_CACHE được áp dụng trực tiếp cho chức năng người dùng, để lại mức tối đa ở giá trị mặc định là 128:

@lru_cache
def count_vowels(sentence):
    return sum(sentence.count(vowel) for vowel in 'AEIOUaeiou')

Nếu tối đa được đặt thành

@lru_cache
def count_vowels(sentence):
    return sum(sentence.count(vowel) for vowel in 'AEIOUaeiou')
8, tính năng LRU sẽ bị tắt và bộ đệm có thể phát triển mà không bị ràng buộc.

Nếu gõ được đặt thành TRUE, các đối số chức năng của các loại khác nhau sẽ được lưu trữ riêng. Nếu gõ là sai, việc thực hiện thường sẽ coi chúng là các cuộc gọi tương đương và chỉ lưu trữ một kết quả duy nhất. (Một số loại như STR và INT có thể được lưu trữ riêng biệt ngay cả khi gõ là sai.)

Lưu ý, loại đặc hiệu chỉ áp dụng cho chức năng đối số ngay lập tức thay vì nội dung của chúng. Các đối số vô hướng,

@lru_cache
def count_vowels(sentence):
    return sum(sentence.count(vowel) for vowel in 'AEIOUaeiou')
9 và
@lru_cache(maxsize=32)
def get_pep(num):
    'Retrieve text of a Python Enhancement Proposal'
    resource = 'https://peps.python.org/pep-%04d/' % num
    try:
        with urllib.request.urlopen(resource) as s:
            return s.read()
    except urllib.error.HTTPError:
        return 'Not Found'

>>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
...     pep = get_pep(n)
...     print(n, len(pep))

>>> get_pep.cache_info()
CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)
0 được coi là các cuộc gọi riêng biệt với kết quả riêng biệt. Ngược lại, các đối số tuple
@lru_cache(maxsize=32)
def get_pep(num):
    'Retrieve text of a Python Enhancement Proposal'
    resource = 'https://peps.python.org/pep-%04d/' % num
    try:
        with urllib.request.urlopen(resource) as s:
            return s.read()
    except urllib.error.HTTPError:
        return 'Not Found'

>>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
...     pep = get_pep(n)
...     print(n, len(pep))

>>> get_pep.cache_info()
CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)
1 và
@lru_cache(maxsize=32)
def get_pep(num):
    'Retrieve text of a Python Enhancement Proposal'
    resource = 'https://peps.python.org/pep-%04d/' % num
    try:
        with urllib.request.urlopen(resource) as s:
            return s.read()
    except urllib.error.HTTPError:
        return 'Not Found'

>>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
...     pep = get_pep(n)
...     print(n, len(pep))

>>> get_pep.cache_info()
CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)
2 được coi là tương đương.

Hàm được bọc được trang bị chức năng

@lru_cache(maxsize=32)
def get_pep(num):
    'Retrieve text of a Python Enhancement Proposal'
    resource = 'https://peps.python.org/pep-%04d/' % num
    try:
        with urllib.request.urlopen(resource) as s:
            return s.read()
    except urllib.error.HTTPError:
        return 'Not Found'

>>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
...     pep = get_pep(n)
...     print(n, len(pep))

>>> get_pep.cache_info()
CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)
3 trả về
@lru_cache(maxsize=32)
def get_pep(num):
    'Retrieve text of a Python Enhancement Proposal'
    resource = 'https://peps.python.org/pep-%04d/' % num
    try:
        with urllib.request.urlopen(resource) as s:
            return s.read()
    except urllib.error.HTTPError:
        return 'Not Found'

>>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
...     pep = get_pep(n)
...     print(n, len(pep))

>>> get_pep.cache_info()
CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)
4 mới hiển thị các giá trị cho tối đa hóa và gõ. Đây là chỉ cho mục đích thông tin. Đột biến các giá trị không có hiệu lực.

Để giúp đo lường hiệu quả của bộ đệm và điều chỉnh tham số tối đa, chức năng được bọc được trang bị chức năng

@lru_cache(maxsize=32)
def get_pep(num):
    'Retrieve text of a Python Enhancement Proposal'
    resource = 'https://peps.python.org/pep-%04d/' % num
    try:
        with urllib.request.urlopen(resource) as s:
            return s.read()
    except urllib.error.HTTPError:
        return 'Not Found'

>>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
...     pep = get_pep(n)
...     print(n, len(pep))

>>> get_pep.cache_info()
CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)
5 trả về một tuple có tên hiển thị các lượt truy cập, bỏ lỡ, tối đa và điều hòa.named tuple showing hits, misses, maxsize and currsize.

Bộ trang trí cũng cung cấp chức năng

@lru_cache(maxsize=32)
def get_pep(num):
    'Retrieve text of a Python Enhancement Proposal'
    resource = 'https://peps.python.org/pep-%04d/' % num
    try:
        with urllib.request.urlopen(resource) as s:
            return s.read()
    except urllib.error.HTTPError:
        return 'Not Found'

>>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
...     pep = get_pep(n)
...     print(n, len(pep))

>>> get_pep.cache_info()
CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)
6 để xóa hoặc vô hiệu hóa bộ đệm.

Hàm cơ bản ban đầu có thể truy cập thông qua thuộc tính

@lru_cache(maxsize=32)
def get_pep(num):
    'Retrieve text of a Python Enhancement Proposal'
    resource = 'https://peps.python.org/pep-%04d/' % num
    try:
        with urllib.request.urlopen(resource) as s:
            return s.read()
    except urllib.error.HTTPError:
        return 'Not Found'

>>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
...     pep = get_pep(n)
...     print(n, len(pep))

>>> get_pep.cache_info()
CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)
7. Điều này rất hữu ích cho nội tâm, để bỏ qua bộ đệm hoặc để viết lại chức năng bằng bộ đệm khác.

Bộ đệm giữ các tham chiếu đến các đối số và trả về các giá trị cho đến khi chúng ra khỏi bộ đệm hoặc cho đến khi bộ đệm được xóa.

Nếu một phương thức được lưu trong bộ nhớ cache, đối số cá thể

@lru_cache(maxsize=32)
def get_pep(num):
    'Retrieve text of a Python Enhancement Proposal'
    resource = 'https://peps.python.org/pep-%04d/' % num
    try:
        with urllib.request.urlopen(resource) as s:
            return s.read()
    except urllib.error.HTTPError:
        return 'Not Found'

>>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
...     pep = get_pep(n)
...     print(n, len(pep))

>>> get_pep.cache_info()
CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)
8 được bao gồm trong bộ đệm. Xem cách tôi gọi bộ nhớ cache?How do I cache method calls?

Bộ đệm LRU (ít được sử dụng gần đây) hoạt động tốt nhất khi các cuộc gọi gần đây nhất là các dự đoán tốt nhất về các cuộc gọi sắp tới (ví dụ: các bài viết phổ biến nhất trên máy chủ tin tức có xu hướng thay đổi mỗi ngày). Giới hạn kích thước bộ đệm của bộ đệm đảm bảo rằng bộ đệm không phát triển mà không bị ràng buộc trên các quy trình chạy dài như máy chủ web.

Nói chung, bộ đệm LRU chỉ nên được sử dụng khi bạn muốn sử dụng lại các giá trị được tính toán trước đó. Theo đó, nó không có ý nghĩa đối với các chức năng bộ đệm với các tác dụng phụ, các chức năng cần tạo các đối tượng có thể thay đổi khác biệt trên mỗi cuộc gọi hoặc các hàm không tinh khiết như thời gian () hoặc ngẫu nhiên ().

Ví dụ về bộ đệm LRU cho nội dung web tĩnh:

@lru_cache(maxsize=32)
def get_pep(num):
    'Retrieve text of a Python Enhancement Proposal'
    resource = 'https://peps.python.org/pep-%04d/' % num
    try:
        with urllib.request.urlopen(resource) as s:
            return s.read()
    except urllib.error.HTTPError:
        return 'Not Found'

>>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
...     pep = get_pep(n)
...     print(n, len(pep))

>>> get_pep.cache_info()
CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)

Ví dụ về các số Fibonacci tính toán hiệu quả bằng cách sử dụng bộ đệm để thực hiện kỹ thuật lập trình động:

@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

>>> [fib(n) for n in range(16)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]

>>> fib.cache_info()
CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)

Mới trong phiên bản 3.2.

Đã thay đổi trong phiên bản 3.3: Đã thêm tùy chọn đánh máy.Added the typed option.

Đã thay đổi trong phiên bản 3.8: Đã thêm tùy chọn user_function.Added the user_function option.

Mới trong phiên bản 3.9: Đã thêm chức năng

@lru_cache(maxsize=32)
def get_pep(num):
    'Retrieve text of a Python Enhancement Proposal'
    resource = 'https://peps.python.org/pep-%04d/' % num
    try:
        with urllib.request.urlopen(resource) as s:
            return s.read()
    except urllib.error.HTTPError:
        return 'Not Found'

>>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
...     pep = get_pep(n)
...     print(n, len(pep))

>>> get_pep.cache_info()
CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)
3Added the function
@lru_cache(maxsize=32)
def get_pep(num):
    'Retrieve text of a Python Enhancement Proposal'
    resource = 'https://peps.python.org/pep-%04d/' % num
    try:
        with urllib.request.urlopen(resource) as s:
            return s.read()
    except urllib.error.HTTPError:
        return 'Not Found'

>>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
...     pep = get_pep(n)
...     print(n, len(pep))

>>> get_pep.cache_info()
CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)
3

@functools.total_ordering¶functools.total_ordering

Đưa ra một lớp xác định một hoặc nhiều phương pháp đặt hàng so sánh phong phú, người trang trí lớp này cung cấp phần còn lại. Điều này đơn giản hóa nỗ lực liên quan đến việc chỉ định tất cả các hoạt động so sánh phong phú có thể có:

Lớp phải xác định một trong

@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

>>> [fib(n) for n in range(16)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]

>>> fib.cache_info()
CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)
0,
@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

>>> [fib(n) for n in range(16)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]

>>> fib.cache_info()
CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)
1,
@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

>>> [fib(n) for n in range(16)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]

>>> fib.cache_info()
CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)
2 hoặc
@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

>>> [fib(n) for n in range(16)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]

>>> fib.cache_info()
CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)
3. Ngoài ra, lớp nên cung cấp một phương pháp
@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

>>> [fib(n) for n in range(16)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]

>>> fib.cache_info()
CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)
4.

Ví dụ:

@total_ordering
class Student:
    def _is_valid_operand(self, other):
        return (hasattr(other, "lastname") and
                hasattr(other, "firstname"))
    def __eq__(self, other):
        if not self._is_valid_operand(other):
            return NotImplemented
        return ((self.lastname.lower(), self.firstname.lower()) ==
                (other.lastname.lower(), other.firstname.lower()))
    def __lt__(self, other):
        if not self._is_valid_operand(other):
            return NotImplemented
        return ((self.lastname.lower(), self.firstname.lower()) <
                (other.lastname.lower(), other.firstname.lower()))

Ghi chú

Mặc dù nhà trang trí này giúp bạn dễ dàng tạo ra các loại hoàn toàn có hành vi tốt, nhưng nó phải chịu chi phí thực hiện chậm hơn và dấu vết ngăn xếp phức tạp hơn cho các phương pháp so sánh dẫn xuất. Nếu điểm chuẩn hiệu suất cho thấy đây là một nút cổ chai cho một ứng dụng nhất định, việc thực hiện tất cả sáu phương pháp so sánh phong phú thay vào đó có khả năng cung cấp một sự tăng tốc độ dễ dàng.

Ghi chú

Mặc dù nhà trang trí này giúp bạn dễ dàng tạo ra các loại hoàn toàn có hành vi tốt, nhưng nó phải chịu chi phí thực hiện chậm hơn và dấu vết ngăn xếp phức tạp hơn cho các phương pháp so sánh dẫn xuất. Nếu điểm chuẩn hiệu suất cho thấy đây là một nút cổ chai cho một ứng dụng nhất định, việc thực hiện tất cả sáu phương pháp so sánh phong phú thay vào đó có khả năng cung cấp một sự tăng tốc độ dễ dàng.

Mới trong phiên bản 3.2.

Đã thay đổi trong phiên bản 3.3: Đã thêm tùy chọn đánh máy.Returning NotImplemented from the underlying comparison function for unrecognised types is now supported.

Đã thay đổi trong phiên bản 3.8: Đã thêm tùy chọn user_function.partial(func, /, *args, **keywords)

Mới trong phiên bản 3.9: Đã thêm chức năng

@lru_cache(maxsize=32)
def get_pep(num):
    'Retrieve text of a Python Enhancement Proposal'
    resource = 'https://peps.python.org/pep-%04d/' % num
    try:
        with urllib.request.urlopen(resource) as s:
            return s.read()
    except urllib.error.HTTPError:
        return 'Not Found'

>>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
...     pep = get_pep(n)
...     print(n, len(pep))

>>> get_pep.cache_info()
CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)
3partial object which when called will behave like func called with the positional arguments args and keyword arguments keywords. If more arguments are supplied to the call, they are appended to args. If additional keyword arguments are supplied, they extend and override keywords. Roughly equivalent to:

def partial(func, /, *args, **keywords):
    def newfunc(*fargs, **fkeywords):
        newkeywords = {**keywords, **fkeywords}
        return func(*args, *fargs, **newkeywords)
    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords
    return newfunc

@functools.total_ordering¶

>>> from functools import partial
>>> basetwo = partial(int, base=2)
>>> basetwo.__doc__ = 'Convert base 2 string to an int.'
>>> basetwo('10010')
18

Đưa ra một lớp xác định một hoặc nhiều phương pháp đặt hàng so sánh phong phú, người trang trí lớp này cung cấp phần còn lại. Điều này đơn giản hóa nỗ lực liên quan đến việc chỉ định tất cả các hoạt động so sánh phong phú có thể có: functools.partialmethod(func, /, *args, **keywords)

Lớp phải xác định một trong

@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

>>> [fib(n) for n in range(16)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]

>>> fib.cache_info()
CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)
0,
@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

>>> [fib(n) for n in range(16)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]

>>> fib.cache_info()
CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)
1,
@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

>>> [fib(n) for n in range(16)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]

>>> fib.cache_info()
CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)
2 hoặc
@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

>>> [fib(n) for n in range(16)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]

>>> fib.cache_info()
CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)
3. Ngoài ra, lớp nên cung cấp một phương pháp
@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

>>> [fib(n) for n in range(16)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]

>>> fib.cache_info()
CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)
4.

Ví dụ:descriptor or a callable (objects which are both, like normal functions, are handled as descriptors).

Ghi chúpartial object returned as the result.

Mặc dù nhà trang trí này giúp bạn dễ dàng tạo ra các loại hoàn toàn có hành vi tốt, nhưng nó phải chịu chi phí thực hiện chậm hơn và dấu vết ngăn xếp phức tạp hơn cho các phương pháp so sánh dẫn xuất. Nếu điểm chuẩn hiệu suất cho thấy đây là một nút cổ chai cho một ứng dụng nhất định, việc thực hiện tất cả sáu phương pháp so sánh phong phú thay vào đó có khả năng cung cấp một sự tăng tốc độ dễ dàng.

Example:

class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)
0

Mới trong phiên bản 3.4.

functools.reduce (chức năng, itable [, infitorSer]) ¶reduce(function, iterable[, initializer])

Áp dụng chức năng của hai đối số tích lũy cho các mục có thể lặp lại, từ trái sang phải, để giảm độ lặp lại thành một giá trị duy nhất. Ví dụ,

@total_ordering
class Student:
    def _is_valid_operand(self, other):
        return (hasattr(other, "lastname") and
                hasattr(other, "firstname"))
    def __eq__(self, other):
        if not self._is_valid_operand(other):
            return NotImplemented
        return ((self.lastname.lower(), self.firstname.lower()) ==
                (other.lastname.lower(), other.firstname.lower()))
    def __lt__(self, other):
        if not self._is_valid_operand(other):
            return NotImplemented
        return ((self.lastname.lower(), self.firstname.lower()) <
                (other.lastname.lower(), other.firstname.lower()))
6 tính toán
@total_ordering
class Student:
    def _is_valid_operand(self, other):
        return (hasattr(other, "lastname") and
                hasattr(other, "firstname"))
    def __eq__(self, other):
        if not self._is_valid_operand(other):
            return NotImplemented
        return ((self.lastname.lower(), self.firstname.lower()) ==
                (other.lastname.lower(), other.firstname.lower()))
    def __lt__(self, other):
        if not self._is_valid_operand(other):
            return NotImplemented
        return ((self.lastname.lower(), self.firstname.lower()) <
                (other.lastname.lower(), other.firstname.lower()))
7. Đối số bên trái, x, là giá trị tích lũy và đối số bên phải, y, là giá trị cập nhật từ có thể điều chỉnh được. Nếu trình khởi tạo tùy chọn có mặt, nó được đặt trước các mục của ITEBLE trong phép tính và đóng vai trò là mặc định khi có thể trống. Nếu bộ khởi tạo không được cung cấp và có thể chỉ có một mục, mục đầu tiên được trả lại.

Tương đương với:

class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)
1

Xem

@total_ordering
class Student:
    def _is_valid_operand(self, other):
        return (hasattr(other, "lastname") and
                hasattr(other, "firstname"))
    def __eq__(self, other):
        if not self._is_valid_operand(other):
            return NotImplemented
        return ((self.lastname.lower(), self.firstname.lower()) ==
                (other.lastname.lower(), other.firstname.lower()))
    def __lt__(self, other):
        if not self._is_valid_operand(other):
            return NotImplemented
        return ((self.lastname.lower(), self.firstname.lower()) <
                (other.lastname.lower(), other.firstname.lower()))
8 để biết trình lặp mang lại tất cả các giá trị trung gian.

@functools.singledispatch¶functools.singledispatch

Chuyển đổi một hàm thành một hàm đơn dispatchgeneric.single-dispatch generic function.

Để xác định một chức năng chung, trang trí nó với bộ trang trí

@total_ordering
class Student:
    def _is_valid_operand(self, other):
        return (hasattr(other, "lastname") and
                hasattr(other, "firstname"))
    def __eq__(self, other):
        if not self._is_valid_operand(other):
            return NotImplemented
        return ((self.lastname.lower(), self.firstname.lower()) ==
                (other.lastname.lower(), other.firstname.lower()))
    def __lt__(self, other):
        if not self._is_valid_operand(other):
            return NotImplemented
        return ((self.lastname.lower(), self.firstname.lower()) <
                (other.lastname.lower(), other.firstname.lower()))
9. Khi xác định chức năng bằng cách sử dụng
@total_ordering
class Student:
    def _is_valid_operand(self, other):
        return (hasattr(other, "lastname") and
                hasattr(other, "firstname"))
    def __eq__(self, other):
        if not self._is_valid_operand(other):
            return NotImplemented
        return ((self.lastname.lower(), self.firstname.lower()) ==
                (other.lastname.lower(), other.firstname.lower()))
    def __lt__(self, other):
        if not self._is_valid_operand(other):
            return NotImplemented
        return ((self.lastname.lower(), self.firstname.lower()) <
                (other.lastname.lower(), other.firstname.lower()))
9, lưu ý rằng công văn xảy ra trên loại đối số đầu tiên:

class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)
2

Để thêm các triển khai quá tải vào hàm, hãy sử dụng thuộc tính

def partial(func, /, *args, **keywords):
    def newfunc(*fargs, **fkeywords):
        newkeywords = {**keywords, **fkeywords}
        return func(*args, *fargs, **newkeywords)
    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords
    return newfunc
1 của hàm chung, có thể được sử dụng làm chất trang trí. Đối với các chức năng được chú thích bằng các loại, người trang trí sẽ tự động suy ra loại đối số đầu tiên:

class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)
3

def partial(func, /, *args, **keywords):
    def newfunc(*fargs, **fkeywords):
        newkeywords = {**keywords, **fkeywords}
        return func(*args, *fargs, **newkeywords)
    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords
    return newfunc
2 và
def partial(func, /, *args, **keywords):
    def newfunc(*fargs, **fkeywords):
        newkeywords = {**keywords, **fkeywords}
        return func(*args, *fargs, **newkeywords)
    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords
    return newfunc
3 cũng có thể được sử dụng:

class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)
4

Đối với mã không sử dụng các chú thích loại, đối số loại thích hợp có thể được chuyển rõ ràng cho chính bộ trang trí:

class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)
5

Để cho phép đăng ký LambDA và các hàm đã tồn tại trước, thuộc tính

def partial(func, /, *args, **keywords):
    def newfunc(*fargs, **fkeywords):
        newkeywords = {**keywords, **fkeywords}
        return func(*args, *fargs, **newkeywords)
    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords
    return newfunc
1 cũng có thể được sử dụng ở dạng chức năng:lambdas and pre-existing functions, the
def partial(func, /, *args, **keywords):
    def newfunc(*fargs, **fkeywords):
        newkeywords = {**keywords, **fkeywords}
        return func(*args, *fargs, **newkeywords)
    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords
    return newfunc
1 attribute can also be used in a functional form:

class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)
6

Thuộc tính

def partial(func, /, *args, **keywords):
    def newfunc(*fargs, **fkeywords):
        newkeywords = {**keywords, **fkeywords}
        return func(*args, *fargs, **newkeywords)
    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords
    return newfunc
1 trả về hàm không được trang trí. Điều này cho phép trang trí xếp chồng,
def partial(func, /, *args, **keywords):
    def newfunc(*fargs, **fkeywords):
        newkeywords = {**keywords, **fkeywords}
        return func(*args, *fargs, **newkeywords)
    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords
    return newfunc
6 và tạo ra các bài kiểm tra đơn vị cho từng biến thể một cách độc lập:

class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)
7

Khi được gọi, chức năng chung gửi về loại đối số đầu tiên:

class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)
8

Trong trường hợp không có triển khai đã đăng ký cho một loại cụ thể, thứ tự phân giải phương thức của nó được sử dụng để tìm một triển khai chung hơn. Hàm ban đầu được trang trí với

@total_ordering
class Student:
    def _is_valid_operand(self, other):
        return (hasattr(other, "lastname") and
                hasattr(other, "firstname"))
    def __eq__(self, other):
        if not self._is_valid_operand(other):
            return NotImplemented
        return ((self.lastname.lower(), self.firstname.lower()) ==
                (other.lastname.lower(), other.firstname.lower()))
    def __lt__(self, other):
        if not self._is_valid_operand(other):
            return NotImplemented
        return ((self.lastname.lower(), self.firstname.lower()) <
                (other.lastname.lower(), other.firstname.lower()))
9 được đăng ký cho loại cơ sở
def partial(func, /, *args, **keywords):
    def newfunc(*fargs, **fkeywords):
        newkeywords = {**keywords, **fkeywords}
        return func(*args, *fargs, **newkeywords)
    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords
    return newfunc
8, điều đó có nghĩa là nó được sử dụng nếu không tìm thấy việc thực hiện tốt hơn.

Nếu một triển khai được đăng ký vào một lớp cơ sở trừu tượng, các lớp con ảo của lớp cơ sở sẽ được gửi đến việc thực hiện đó:abstract base class, virtual subclasses of the base class will be dispatched to that implementation:

class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)
9

Để kiểm tra triển khai nào chức năng chung sẽ chọn cho một loại đã cho, hãy sử dụng thuộc tính

def partial(func, /, *args, **keywords):
    def newfunc(*fargs, **fkeywords):
        newkeywords = {**keywords, **fkeywords}
        return func(*args, *fargs, **newkeywords)
    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords
    return newfunc
9:

class DataSet:
    def __init__(self, sequence_of_numbers):
        self._data = sequence_of_numbers

    @property
    @cache
    def stdev(self):
        return statistics.stdev(self._data)
0

Để truy cập tất cả các triển khai đã đăng ký, hãy sử dụng thuộc tính

>>> from functools import partial
>>> basetwo = partial(int, base=2)
>>> basetwo.__doc__ = 'Convert base 2 string to an int.'
>>> basetwo('10010')
18
0 chỉ đọc:

class DataSet:
    def __init__(self, sequence_of_numbers):
        self._data = sequence_of_numbers

    @property
    @cache
    def stdev(self):
        return statistics.stdev(self._data)
1

Mới trong phiên bản 3.4.

Đã thay đổi trong phiên bản 3.7: Thuộc tính

def partial(func, /, *args, **keywords):
    def newfunc(*fargs, **fkeywords):
        newkeywords = {**keywords, **fkeywords}
        return func(*args, *fargs, **newkeywords)
    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords
    return newfunc
1 hiện hỗ trợ bằng cách sử dụng các chú thích loại.The
def partial(func, /, *args, **keywords):
    def newfunc(*fargs, **fkeywords):
        newkeywords = {**keywords, **fkeywords}
        return func(*args, *fargs, **newkeywords)
    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords
    return newfunc
1 attribute now supports using type annotations.

Đã thay đổi trong phiên bản 3.11: Thuộc tính

def partial(func, /, *args, **keywords):
    def newfunc(*fargs, **fkeywords):
        newkeywords = {**keywords, **fkeywords}
        return func(*args, *fargs, **newkeywords)
    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords
    return newfunc
1 hiện hỗ trợ
def partial(func, /, *args, **keywords):
    def newfunc(*fargs, **fkeywords):
        newkeywords = {**keywords, **fkeywords}
        return func(*args, *fargs, **newkeywords)
    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords
    return newfunc
2 và
def partial(func, /, *args, **keywords):
    def newfunc(*fargs, **fkeywords):
        newkeywords = {**keywords, **fkeywords}
        return func(*args, *fargs, **newkeywords)
    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords
    return newfunc
3 dưới dạng chú thích loại.The
def partial(func, /, *args, **keywords):
    def newfunc(*fargs, **fkeywords):
        newkeywords = {**keywords, **fkeywords}
        return func(*args, *fargs, **newkeywords)
    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords
    return newfunc
1 attribute now supports
def partial(func, /, *args, **keywords):
    def newfunc(*fargs, **fkeywords):
        newkeywords = {**keywords, **fkeywords}
        return func(*args, *fargs, **newkeywords)
    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords
    return newfunc
2 and
def partial(func, /, *args, **keywords):
    def newfunc(*fargs, **fkeywords):
        newkeywords = {**keywords, **fkeywords}
        return func(*args, *fargs, **newkeywords)
    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords
    return newfunc
3 as type annotations.

classfunctionools.singledispatchmethod (func) ¶ functools.singledispatchmethod(func)

Chuyển đổi một phương thức thành một hàm đơn dispatchgeneric.single-dispatch generic function.

Để xác định một phương pháp chung, trang trí nó với bộ trang trí

>>> from functools import partial
>>> basetwo = partial(int, base=2)
>>> basetwo.__doc__ = 'Convert base 2 string to an int.'
>>> basetwo('10010')
18
5. Khi xác định chức năng bằng cách sử dụng
>>> from functools import partial
>>> basetwo = partial(int, base=2)
>>> basetwo.__doc__ = 'Convert base 2 string to an int.'
>>> basetwo('10010')
18
5, lưu ý rằng việc điều phối xảy ra trên loại đối số không phải hoặc không CLS đầu tiên:

class DataSet:
    def __init__(self, sequence_of_numbers):
        self._data = sequence_of_numbers

    @property
    @cache
    def stdev(self):
        return statistics.stdev(self._data)
2

>>> from functools import partial
>>> basetwo = partial(int, base=2)
>>> basetwo.__doc__ = 'Convert base 2 string to an int.'
>>> basetwo('10010')
18
5 hỗ trợ làm tổ với các nhà trang trí khác như
>>> from functools import partial
>>> basetwo = partial(int, base=2)
>>> basetwo.__doc__ = 'Convert base 2 string to an int.'
>>> basetwo('10010')
18
8. Lưu ý rằng để cho phép
>>> from functools import partial
>>> basetwo = partial(int, base=2)
>>> basetwo.__doc__ = 'Convert base 2 string to an int.'
>>> basetwo('10010')
18
9,
class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)
00 phải là nhà trang trí bên ngoài nhất. Dưới đây là lớp
class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)
01 với các phương thức
class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)
02 được liên kết với lớp, thay vì một thể hiện của lớp:

class DataSet:
    def __init__(self, sequence_of_numbers):
        self._data = sequence_of_numbers

    @property
    @cache
    def stdev(self):
        return statistics.stdev(self._data)
3

Mô hình tương tự có thể được sử dụng cho các nhà trang trí tương tự khác:

class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)
03,
class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)
04 và các mô hình khác.

Mới trong phiên bản 3.8.

functools.update_wrapper (bao bọc, được bọc, gán = wrapper_assignments, update = wrapper_updates) ¶update_wrapper(wrapper, wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)

Cập nhật chức năng trình bao bọc để trông giống như chức năng được bọc. Các đối số tùy chọn là bộ dữ liệu để chỉ định thuộc tính nào của hàm gốc được gán trực tiếp cho các thuộc tính phù hợp trên hàm trình bao bọc và thuộc tính nào của hàm trình bao được cập nhật với các thuộc tính tương ứng từ hàm gốc. Các giá trị mặc định cho các đối số này là các hằng số cấp mô -đun

class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)
05 (gán cho hàm trình bao bọc, ____ ____106,
class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)
07,
class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)
08,
class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)
09 và
class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)
10, chuỗi tài liệu) và
class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)
11 (cập nhật chức năng trình bao bọc ____.

Để cho phép truy cập vào chức năng ban đầu cho các mục đích nội tâm và các mục đích khác (ví dụ: bỏ qua một trình trang trí bộ đệm như

class DataSet:
    def __init__(self, sequence_of_numbers):
        self._data = sequence_of_numbers

    @property
    @cache
    def stdev(self):
        return statistics.stdev(self._data)
8), hàm này sẽ tự động thêm thuộc tính
@lru_cache(maxsize=32)
def get_pep(num):
    'Retrieve text of a Python Enhancement Proposal'
    resource = 'https://peps.python.org/pep-%04d/' % num
    try:
        with urllib.request.urlopen(resource) as s:
            return s.read()
    except urllib.error.HTTPError:
        return 'Not Found'

>>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
...     pep = get_pep(n)
...     print(n, len(pep))

>>> get_pep.cache_info()
CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)
7 cho trình bao bọc đề cập đến chức năng được gói.

Việc sử dụng chính cho chức năng này là trong các chức năng trang trí bao bọc chức năng được trang trí và trả lại trình bao bọc. Nếu hàm trình bao bọc không được cập nhật, siêu dữ liệu của hàm được trả về sẽ phản ánh định nghĩa trình bao bọc thay vì định nghĩa hàm gốc, thường ít hơn hữu ích.decorator functions which wrap the decorated function and return the wrapper. If the wrapper function is not updated, the metadata of the returned function will reflect the wrapper definition rather than the original function definition, which is typically less than helpful.

class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)
15 có thể được sử dụng với các vật liệu gọi khác với các chức năng. Bất kỳ thuộc tính nào được đặt tên trong được gán hoặc cập nhật bị thiếu từ đối tượng bị bọc đều bị bỏ qua (nghĩa là chức năng này sẽ không cố gắng đặt chúng trên hàm trình bao bọc).
class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)
16 vẫn được nâng lên nếu chính chức năng trình bao bọc bị thiếu bất kỳ thuộc tính nào có tên được cập nhật.

Mới trong phiên bản 3.2: Tự động bổ sung thuộc tính

@lru_cache(maxsize=32)
def get_pep(num):
    'Retrieve text of a Python Enhancement Proposal'
    resource = 'https://peps.python.org/pep-%04d/' % num
    try:
        with urllib.request.urlopen(resource) as s:
            return s.read()
    except urllib.error.HTTPError:
        return 'Not Found'

>>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
...     pep = get_pep(n)
...     print(n, len(pep))

>>> get_pep.cache_info()
CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)
7.Automatic addition of the
@lru_cache(maxsize=32)
def get_pep(num):
    'Retrieve text of a Python Enhancement Proposal'
    resource = 'https://peps.python.org/pep-%04d/' % num
    try:
        with urllib.request.urlopen(resource) as s:
            return s.read()
    except urllib.error.HTTPError:
        return 'Not Found'

>>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
...     pep = get_pep(n)
...     print(n, len(pep))

>>> get_pep.cache_info()
CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)
7 attribute.

Mới trong phiên bản 3.2: Sao chép thuộc tính

class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)
09 theo mặc định.Copying of the
class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)
09 attribute by default.

Đã thay đổi trong phiên bản 3.2: Thiếu các thuộc tính không còn kích hoạt

class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)
16.Missing attributes no longer trigger an
class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)
16.

Đã thay đổi trong phiên bản 3.4: Thuộc tính

@lru_cache(maxsize=32)
def get_pep(num):
    'Retrieve text of a Python Enhancement Proposal'
    resource = 'https://peps.python.org/pep-%04d/' % num
    try:
        with urllib.request.urlopen(resource) as s:
            return s.read()
    except urllib.error.HTTPError:
        return 'Not Found'

>>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
...     pep = get_pep(n)
...     print(n, len(pep))

>>> get_pep.cache_info()
CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)
7 hiện luôn đề cập đến hàm được bọc, ngay cả khi hàm đó xác định thuộc tính
@lru_cache(maxsize=32)
def get_pep(num):
    'Retrieve text of a Python Enhancement Proposal'
    resource = 'https://peps.python.org/pep-%04d/' % num
    try:
        with urllib.request.urlopen(resource) as s:
            return s.read()
    except urllib.error.HTTPError:
        return 'Not Found'

>>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
...     pep = get_pep(n)
...     print(n, len(pep))

>>> get_pep.cache_info()
CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)
7. (Xem BPO-17482)The
@lru_cache(maxsize=32)
def get_pep(num):
    'Retrieve text of a Python Enhancement Proposal'
    resource = 'https://peps.python.org/pep-%04d/' % num
    try:
        with urllib.request.urlopen(resource) as s:
            return s.read()
    except urllib.error.HTTPError:
        return 'Not Found'

>>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
...     pep = get_pep(n)
...     print(n, len(pep))

>>> get_pep.cache_info()
CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)
7 attribute now always refers to the wrapped function, even if that function defined a
@lru_cache(maxsize=32)
def get_pep(num):
    'Retrieve text of a Python Enhancement Proposal'
    resource = 'https://peps.python.org/pep-%04d/' % num
    try:
        with urllib.request.urlopen(resource) as s:
            return s.read()
    except urllib.error.HTTPError:
        return 'Not Found'

>>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
...     pep = get_pep(n)
...     print(n, len(pep))

>>> get_pep.cache_info()
CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)
7 attribute. (see bpo-17482)

@functools.wraps (được bao bọc, gán = wrapper_assignments, ended = wrapper_updates) ¶functools.wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)

Đây là một chức năng thuận tiện để gọi

class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)
15 như một trình trang trí chức năng khi xác định hàm trình bao bọc. Nó tương đương với
class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)
23. Ví dụ:

class DataSet:
    def __init__(self, sequence_of_numbers):
        self._data = sequence_of_numbers

    @property
    @cache
    def stdev(self):
        return statistics.stdev(self._data)
4

Nếu không sử dụng nhà máy trang trí này, tên của hàm ví dụ sẽ là

class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)
24 và tài liệu của
class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)
25 ban đầu sẽ bị mất.

@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

>>> [fib(n) for n in range(16)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]

>>> fib.cache_info()
CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)
9 Đối tượng

Các đối tượng

@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

>>> [fib(n) for n in range(16)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]

>>> fib.cache_info()
CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)
9 là các đối tượng có thể gọi được được tạo bởi
@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

>>> [fib(n) for n in range(16)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]

>>> fib.cache_info()
CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)
5. Họ có ba thuộc tính chỉ đọc:

một phần.func¶func

Một đối tượng hoặc chức năng có thể gọi được. Các cuộc gọi đến đối tượng

@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

>>> [fib(n) for n in range(16)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]

>>> fib.cache_info()
CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)
9 sẽ được chuyển tiếp đến
class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)
30 với các đối số và từ khóa mới.

một phần.Args¶args

Các đối số vị trí ngoài cùng bên trái sẽ được chuẩn bị cho các đối số vị trí được cung cấp cho cuộc gọi đối tượng

@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

>>> [fib(n) for n in range(16)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]

>>> fib.cache_info()
CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)
9.

Partial.Keywords¶keywords

Các đối số từ khóa sẽ được cung cấp khi đối tượng

@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

>>> [fib(n) for n in range(16)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]

>>> fib.cache_info()
CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)
9 được gọi.

Các đối tượng

@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

>>> [fib(n) for n in range(16)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]

>>> fib.cache_info()
CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)
9 giống như các đối tượng
class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)
34 ở chỗ chúng có thể gọi được, tham chiếu yếu và có thể có các thuộc tính. Có một số khác biệt quan trọng. Chẳng hạn, các thuộc tính
class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)
07 và
class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)
10 không được tạo tự động. Ngoài ra, các đối tượng
@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

>>> [fib(n) for n in range(16)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]

>>> fib.cache_info()
CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)
9 được xác định trong các lớp hoạt động như các phương thức tĩnh và không chuyển đổi thành các phương thức bị ràng buộc trong quá trình tra cứu thuộc tính.