Hướng dẫn python data model class example - ví dụ về lớp mô hình dữ liệu python

3.1. Đối tượng, giá trị và loạiObjects, values and types¶

Các đối tượng là sự trừu tượng của Python cho dữ liệu. Tất cả dữ liệu trong chương trình Python được biểu thị bằng các đối tượng hoặc bằng mối quan hệ giữa các đối tượng. .

Mỗi đối tượng có một danh tính, một loại và một giá trị. Một đối tượng Nhận dạng không bao giờ thay đổi khi nó đã được tạo ra; Bạn có thể nghĩ về nó như là địa chỉ đối tượng trong bộ nhớ. Toán tử ‘

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
5 so sánh danh tính của hai đối tượng; Hàm
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
6 trả về một số nguyên đại diện cho danh tính của nó.

Chi tiết triển khai CPYThon: Đối với CPyThon,

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
7 là địa chỉ bộ nhớ nơi
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
8 được lưu trữ.
For CPython,
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
7 is the memory address where
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
8 is stored.

Một loại đối tượng Xác định các hoạt động mà đối tượng hỗ trợ [ví dụ:, nó có độ dài không? Hàm

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
9 trả về một loại đối tượng [chính là một đối tượng]. Giống như danh tính của nó, một loại đối tượng cũng không thể thay đổi. 1

Giá trị của một số đối tượng có thể thay đổi. Các đối tượng có giá trị có thể thay đổi được cho là có thể thay đổi; Các đối tượng có giá trị không thể thay đổi một khi chúng được tạo ra được gọi là bất biến. . Giống như có một giá trị không thể thay đổi, nó tinh tế hơn.] Khả năng đột biến của một đối tượng được xác định bởi loại của nó; Ví dụ, số, chuỗi và bộ dữ liệu là bất biến, trong khi từ điển và danh sách là có thể thay đổi.

Các đối tượng không bao giờ bị phá hủy rõ ràng; Tuy nhiên, khi chúng không thể truy cập được, chúng có thể được thu thập rác. Việc triển khai được phép hoãn thu thập rác hoặc bỏ qua hoàn toàn - đó là vấn đề về chất lượng thực hiện cách thực hiện bộ sưu tập rác, miễn là không có đối tượng nào được thu thập vẫn có thể truy cập được.

Chi tiết triển khai CPYThon: CPYThon hiện sử dụng sơ đồ đếm tham chiếu với [tùy chọn] phát hiện rác thải được liên kết theo chu kỳ, thu thập hầu hết các đối tượng ngay khi chúng không thể truy cập được, nhưng không được đảm bảo thu thập rác có chứa các tài liệu tham khảo tròn. Xem tài liệu của mô -đun

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
0 để biết thông tin về việc kiểm soát việc thu thập rác tuần hoàn. Các triển khai khác hành động khác nhau và Cpython có thể thay đổi. Không phụ thuộc vào việc hoàn thiện ngay lập tức các đối tượng khi chúng không thể truy cập được [vì vậy bạn nên luôn đóng các tệp một cách rõ ràng]. CPython currently uses a reference-counting scheme with [optional] delayed detection of cyclically linked garbage, which collects most objects as soon as they become unreachable, but is not guaranteed to collect garbage containing circular references. See the documentation of the
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
0 module for information on controlling the collection of cyclic garbage. Other implementations act differently and CPython may change. Do not depend on immediate finalization of objects when they become unreachable [so you should always close files explicitly].

Lưu ý rằng việc sử dụng các cơ sở theo dõi hoặc gỡ lỗi của triển khai có thể giữ cho các đối tượng còn sống thường có thể thu thập được. Cũng lưu ý rằng việc bắt một ngoại lệ với tuyên bố ‘____ ____ 21 ____ ____ 22 22 có thể giữ cho các đối tượng tồn tại.

Một số đối tượng chứa các tham chiếu đến các tài nguyên bên ngoài của các tài nguyên bên ngoài như các tệp mở hoặc cửa sổ. Điều này được hiểu rằng các tài nguyên này được giải phóng khi đối tượng được thu thập rác, nhưng vì việc thu gom rác không được đảm bảo xảy ra, các đối tượng đó cũng cung cấp một cách rõ ràng để giải phóng tài nguyên bên ngoài, thường là phương thức

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
3. Các chương trình được khuyến nghị mạnh mẽ để đóng rõ ràng các đối tượng như vậy. Tuyên bố ‘____ ____ 21 ____ ____ ____ 25 và tuyên bố‘
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
6, cung cấp các cách thuận tiện để làm điều này.

Một số đối tượng chứa các tham chiếu đến các đối tượng khác; Chúng được gọi là container. Ví dụ về các thùng chứa là bộ dữ liệu, danh sách và từ điển. Các tài liệu tham khảo là một phần của giá trị container. Trong hầu hết các trường hợp, khi chúng ta nói về giá trị của một container, chúng ta ngụ ý các giá trị, chứ không phải danh tính của các đối tượng chứa; Tuy nhiên, khi chúng ta nói về khả năng đột biến của một container, chỉ có danh tính của các đối tượng chứa ngay lập tức được ngụ ý. Vì vậy, nếu một thùng chứa bất biến [như một tuple] chứa một tham chiếu đến một đối tượng có thể thay đổi, giá trị của nó sẽ thay đổi nếu đối tượng có thể thay đổi bị thay đổi.

Các loại ảnh hưởng đến hầu hết tất cả các khía cạnh của hành vi đối tượng. Ngay cả tầm quan trọng của nhận dạng đối tượng cũng bị ảnh hưởng theo một nghĩa nào đó: đối với các loại bất biến, các hoạt động tính toán các giá trị mới thực sự có thể trả về một tham chiếu cho bất kỳ đối tượng hiện có nào có cùng loại và giá trị, trong khi đối với các đối tượng có thể thay đổi, điều này không được phép. Ví dụ: sau

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
7,
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
8 và
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
9 có thể hoặc không thể đề cập đến cùng một đối tượng với giá trị một, tùy thuộc vào việc thực hiện, nhưng sau
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
0,
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
1 và
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
2 được đảm bảo để chỉ hai danh sách trống, duy nhất, mới được tạo. [Lưu ý rằng
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
3 gán cùng một đối tượng cho cả
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
1 và
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
2.]

3.2. Phân cấp loại tiêu chuẩnThe standard type hierarchy¶

Dưới đây là danh sách các loại được tích hợp vào Python. Các mô -đun mở rộng [được viết bằng C, Java hoặc các ngôn ngữ khác, tùy thuộc vào việc thực hiện] có thể xác định các loại bổ sung. Các phiên bản Python trong tương lai có thể thêm các loại vào phân cấp loại [ví dụ: số hợp lý, các mảng số nguyên được lưu trữ hiệu quả, v.v.], mặc dù các bổ sung đó thường sẽ được cung cấp thông qua thư viện tiêu chuẩn thay thế.

Một số mô tả loại bên dưới có chứa một danh sách đoạn văn ‘Thuộc tính đặc biệt. Đây là các thuộc tính cung cấp quyền truy cập vào việc thực hiện và không dành cho sử dụng chung. Định nghĩa của họ có thể thay đổi trong tương lai.

Không có

Loại này có một giá trị duy nhất. Có một đối tượng duy nhất với giá trị này. Đối tượng này được truy cập thông qua tên tích hợp

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
6. Nó được sử dụng để biểu thị sự vắng mặt của một giá trị trong nhiều tình huống, ví dụ, nó được trả lại từ các chức năng mà don don rõ ràng trả lại bất cứ điều gì. Giá trị sự thật của nó là sai.

Không được thực hiện

Loại này có một giá trị duy nhất. Có một đối tượng duy nhất với giá trị này. Đối tượng này được truy cập thông qua tên tích hợp

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
7. Các phương thức số và các phương thức so sánh phong phú sẽ trả về giá trị này nếu chúng không thực hiện hoạt động cho các toán hạng được cung cấp. [Sau đó, trình thông dịch sẽ thử hoạt động phản xạ hoặc một số dự phòng khác, tùy thuộc vào toán tử.] Nó không nên được đánh giá trong bối cảnh Boolean.

Xem thực hiện các hoạt động số học để biết thêm chi tiết.Implementing the arithmetic operations for more details.

Thay đổi trong phiên bản 3.9: Đánh giá

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
7 trong bối cảnh Boolean không được chấp nhận. Mặc dù nó hiện đang đánh giá là đúng, nhưng nó sẽ phát ra một
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
9. Nó sẽ tăng
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
0 trong một phiên bản Python trong tương lai.Evaluating
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
7 in a boolean context is deprecated. While it currently evaluates as true, it will emit a
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
9. It will raise a
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
0 in a future version of Python.

Ellipsis

Loại này có một giá trị duy nhất. Có một đối tượng duy nhất với giá trị này. Đối tượng này được truy cập thông qua nghĩa đen

class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
1 hoặc tên tích hợp
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
2. Giá trị sự thật của nó là đúng.

class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
3

Chúng được tạo ra bởi các chữ số và được trả về làm kết quả của các toán tử số học và các hàm tích hợp số học. Các đối tượng số là bất biến; Sau khi tạo ra giá trị của họ không bao giờ thay đổi. Các số Python tất nhiên có liên quan mạnh mẽ đến các số toán học, nhưng tuân theo những hạn chế của biểu diễn số trong máy tính.

Các biểu diễn chuỗi của các lớp số, được tính toán bởi

class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
4 và
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
5, có các thuộc tính sau:

  • Chúng là những chữ số hợp lệ, khi được chuyển cho hàm tạo lớp của chúng, tạo ra một đối tượng có giá trị của số gốc.

  • Đại diện là trong cơ sở 10, khi có thể.

  • Các số không hàng đầu, có thể ngoại trừ một số 0 trước một điểm thập phân, không được hiển thị.

  • Trailing Zeros, có thể ngoại trừ một số 0 sau một điểm thập phân, không được hiển thị.

  • Một dấu hiệu chỉ được hiển thị khi số là âm.

Python phân biệt giữa số nguyên, số điểm nổi và số phức:

class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
6

Chúng đại diện cho các yếu tố từ tập hợp các số nguyên [tích cực và tiêu cực].

Có hai loại số nguyên:

Số nguyên [
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
7]

Chúng đại diện cho các số trong một phạm vi không giới hạn, chỉ có bộ nhớ [ảo] chỉ có sẵn. Với mục đích hoạt động thay đổi và mặt nạ, một biểu diễn nhị phân được giả định và các số âm được biểu diễn trong một biến thể của 2 bổ sung 2, tạo ảo giác về một chuỗi các bit dấu hiệu vô hạn kéo dài sang trái.

Booleans [
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
8]

Chúng đại diện cho các giá trị sự thật sai lầm và đúng. Hai đối tượng đại diện cho các giá trị

class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
9 và
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
0 là các đối tượng boolean duy nhất. Loại Boolean là một kiểu con của loại số nguyên và các giá trị Boolean hoạt động giống như các giá trị 0 và 1, trong hầu hết các bối cảnh, ngoại lệ là khi được chuyển đổi thành một chuỗi, các chuỗi
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
1 hoặc
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
2 được trả về.

Các quy tắc cho biểu diễn số nguyên được dự định để đưa ra cách giải thích có ý nghĩa nhất về các hoạt động thay đổi và mặt nạ liên quan đến các số nguyên âm.

class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
3 [
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
4]

Chúng đại diện cho số điểm nổi độ chính xác kép ở cấp độ máy. Bạn đang ở trong lòng thương xót của kiến ​​trúc máy cơ bản [và triển khai C hoặc Java] cho phạm vi được chấp nhận và xử lý tràn. Python không hỗ trợ số điểm nổi chính xác đơn; Tiết kiệm trong bộ xử lý và sử dụng bộ nhớ thường là lý do để sử dụng chúng bị lấn át bởi chi phí sử dụng các đối tượng trong Python, do đó không có lý do gì để làm phức tạp ngôn ngữ với hai loại số điểm nổi.

class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
5 [
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
6]

Chúng đại diện cho các số phức tạp như một cặp số điểm nổi độ chính xác kép ở cấp độ máy. Các cảnh báo tương tự áp dụng như đối với số điểm nổi. Các phần thực và tưởng tượng của một số phức

class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
7 có thể được truy xuất thông qua các thuộc tính chỉ đọc
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
8 và
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
9.

Trình tự

Chúng đại diện cho các tập hợp được đặt hàng hữu hạn được lập chỉ mục bởi các số không âm. Hàm tích hợp

from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
0 trả về số lượng mục của một chuỗi. Khi độ dài của một chuỗi là n, tập chỉ mục chứa các số 0, 1, phạm, n-1. Mục I của chuỗi A được chọn bởi
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
1.

Trình tự cũng hỗ trợ cắt lát:

from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
2 chọn tất cả các mục với chỉ mục k sao cho i
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
3 k
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
4 j. Khi được sử dụng làm biểu thức, một lát là một chuỗi cùng loại. Điều này ngụ ý rằng bộ chỉ mục được đánh số lại để nó bắt đầu ở 0.

Một số trình tự cũng hỗ trợ cho việc cắt lát mở rộng của người dùng với tham số bước thứ ba của nhóm:

from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
5 chọn tất cả các mục của A với chỉ mục X trong đó
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
6, n
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
7
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
8 và I
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
3 x
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
4 j.

Trình tự được phân biệt theo khả năng đột biến của chúng:

Trình tự bất biến

Một đối tượng thuộc loại trình tự bất biến không thể thay đổi khi nó được tạo. .

Các loại sau là trình tự bất biến:

Dây

Một chuỗi là một chuỗi các giá trị đại diện cho các điểm mã Unicode. Tất cả các điểm mã trong phạm vi

>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

1 có thể được biểu diễn trong một chuỗi. Python không có loại char; Thay vào đó, mọi điểm mã trong chuỗi được biểu diễn dưới dạng đối tượng chuỗi có độ dài
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

2. Hàm tích hợp
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

3 chuyển đổi một điểm mã từ dạng chuỗi của nó thành một số nguyên trong phạm vi
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

4;
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

5 Chuyển đổi một số nguyên trong phạm vi
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

4 thành chiều dài tương ứng
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

2 đối tượng chuỗi.
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

8 có thể được sử dụng để chuyển đổi
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

9 thành
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

0 bằng cách sử dụng mã hóa văn bản đã cho và
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

1 có thể được sử dụng để đạt được điều ngược lại.char type; instead, every code point in the string is represented as a string object with length
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

2. The built-in function
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

3 converts a code point from its string form to an integer in the range
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

4;
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

5 converts an integer in the range
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

4 to the corresponding length
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

2 string object.
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

8 can be used to convert a
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

9 to
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

0 using the given text encoding, and
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

1 can be used to achieve the opposite.

Bộ dữ liệu

Các mục của một tuple là các đối tượng Python tùy ý. Bộ dữ liệu của hai hoặc nhiều mục được hình thành bởi các danh sách các biểu thức được phân tách bằng dấu phẩy. Một bộ của một mục [một singleton,] có thể được hình thành bằng cách gắn dấu phẩy vào một biểu thức [bản thân một biểu thức không tạo ra một tuple, vì dấu ngoặc đơn phải có thể sử dụng để nhóm các biểu thức]. Một tuple trống có thể được hình thành bởi một cặp dấu ngoặc đơn trống.

Byte

Đối tượng byte là một mảng bất biến. Các mục là các byte 8 bit, được biểu thị bằng các số nguyên trong phạm vi 0

Trình tự đột biến

Trình tự có thể thay đổi có thể được thay đổi sau khi chúng được tạo. Các ký hiệu đăng ký và cắt lát có thể được sử dụng làm mục tiêu của các câu lệnh gán và

>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

5 [xóa].

Hiện tại có hai loại trình tự đột biến nội tại:

Danh sách

Các mục của một danh sách là các đối tượng Python tùy ý. Danh sách được hình thành bằng cách đặt một danh sách các biểu thức được phân tách bằng dấu phẩy trong ngoặc vuông. [Lưu ý rằng không có trường hợp đặc biệt cần thiết để hình thành danh sách độ dài 0 hoặc 1.]

Mảng byte

Một đối tượng bytearray là một mảng có thể thay đổi. Chúng được tạo ra bởi hàm tạo

>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

6 tích hợp. Ngoài việc bị thay đổi [và do đó không thể vượt qua], các mảng byte khác cung cấp cùng một giao diện và chức năng như các đối tượng
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

0 bất biến.

Mô -đun mở rộng

>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

8 cung cấp một ví dụ bổ sung về loại chuỗi có thể thay đổi, cũng như mô -đun
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

9.

Đặt loại

Chúng đại diện cho các tập hợp hữu hạn, hữu hạn của các đối tượng độc đáo, bất biến. Như vậy, họ không thể được lập chỉ mục bởi bất kỳ chỉ số nào. Tuy nhiên, chúng có thể được lặp lại và hàm tích hợp

from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
0 trả về số lượng mục trong một bộ. Sử dụng phổ biến cho các bộ là thử nghiệm thành viên nhanh, loại bỏ các bản sao khỏi một chuỗi và các hoạt động toán học như giao lộ, liên kết, khác biệt và sự khác biệt đối xứng.

Đối với các yếu tố đặt, các quy tắc bất biến tương tự áp dụng như đối với các khóa từ điển. Lưu ý rằng các loại số tuân theo các quy tắc thông thường để so sánh số: nếu hai số so sánh bằng nhau [ví dụ:

>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

2 và
>>> class C:
...     pass
...
>>> c = C[]
>>> c.__len__ = lambda: 5
>>> len[c]
Traceback [most recent call last]:
  File "", line 1, in 
TypeError: object of type 'C' has no len[]
2], chỉ có một trong số chúng có thể được chứa trong một tập hợp.

Hiện tại có hai loại bộ nội tại:

Bộ

Chúng đại diện cho một bộ có thể thay đổi. Chúng được tạo bởi hàm tạo

>>> class C:
...     pass
...
>>> c = C[]
>>> c.__len__ = lambda: 5
>>> len[c]
Traceback [most recent call last]:
  File "", line 1, in 
TypeError: object of type 'C' has no len[]
3 tích hợp và có thể được sửa đổi sau đó bằng một số phương pháp, chẳng hạn như
>>> class C:
...     pass
...
>>> c = C[]
>>> c.__len__ = lambda: 5
>>> len[c]
Traceback [most recent call last]:
  File "", line 1, in 
TypeError: object of type 'C' has no len[]
4.

Bộ đông lạnh

Chúng đại diện cho một bộ bất biến. Chúng được tạo ra bởi hàm tạo

>>> class C:
...     pass
...
>>> c = C[]
>>> c.__len__ = lambda: 5
>>> len[c]
Traceback [most recent call last]:
  File "", line 1, in 
TypeError: object of type 'C' has no len[]
5 tích hợp. Vì một chiếc Frozenset là bất biến và có thể băm, nó có thể được sử dụng lại như một yếu tố của một tập hợp khác hoặc như một khóa từ điển.hashable, it can be used again as an element of another set, or as a dictionary key.

Ánh xạ

Chúng đại diện cho các bộ đối tượng hữu hạn được lập chỉ mục bởi các bộ chỉ mục tùy ý. Ký hiệu đăng ký

>>> class C:
...     pass
...
>>> c = C[]
>>> c.__len__ = lambda: 5
>>> len[c]
Traceback [most recent call last]:
  File "", line 1, in 
TypeError: object of type 'C' has no len[]
6 chọn mục được lập chỉ mục bởi
>>> class C:
...     pass
...
>>> c = C[]
>>> c.__len__ = lambda: 5
>>> len[c]
Traceback [most recent call last]:
  File "", line 1, in 
TypeError: object of type 'C' has no len[]
7 từ ánh xạ
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
8; Điều này có thể được sử dụng trong các biểu thức và là mục tiêu của các bài tập hoặc câu lệnh
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

5. Hàm tích hợp
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
0 trả về số lượng mục trong ánh xạ.

Hiện tại có một loại ánh xạ nội tại duy nhất:

Từ điển

Chúng đại diện cho các tập hợp hữu hạn của các đối tượng được lập chỉ mục gần như các giá trị tùy ý. Các loại giá trị duy nhất không được chấp nhận vì các khóa là các giá trị chứa danh sách hoặc từ điển hoặc các loại có thể thay đổi khác được so sánh theo giá trị thay vì nhận dạng đối tượng, lý do là việc thực hiện từ điển hiệu quả đòi hỏi giá trị băm khóa khóa vẫn không đổi. Các loại số được sử dụng cho các khóa tuân thủ các quy tắc thông thường để so sánh số: nếu hai số so sánh bằng nhau [ví dụ:

>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

2 và
>>> class C:
...     pass
...
>>> c = C[]
>>> c.__len__ = lambda: 5
>>> len[c]
Traceback [most recent call last]:
  File "", line 1, in 
TypeError: object of type 'C' has no len[]
2] thì chúng có thể được sử dụng thay thế cho nhau để lập chỉ mục cùng một mục từ điển.

Từ điển bảo tồn thứ tự chèn, có nghĩa là các khóa sẽ được sản xuất theo cùng thứ tự, chúng đã được thêm tuần tự qua từ điển. Thay thế một khóa hiện có không thay đổi thứ tự, tuy nhiên việc loại bỏ một khóa và đặt lại nó sẽ thêm nó vào cuối thay vì giữ vị trí cũ của nó.

Từ điển có thể thay đổi; Chúng có thể được tạo bởi ký hiệu

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
03 [xem phần hiển thị từ điển].Dictionary displays].

Các mô -đun mở rộng

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
04 và
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
05 cung cấp các ví dụ bổ sung về các loại ánh xạ, cũng như mô -đun
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

9.

Đã thay đổi trong phiên bản 3.7: Từ điển không bảo tồn thứ tự chèn trong các phiên bản của Python trước 3.6. Trong Cpython 3.6, thứ tự chèn đã được bảo tồn, nhưng nó được coi là một chi tiết thực hiện tại thời điểm đó thay vì đảm bảo ngôn ngữ.Dictionaries did not preserve insertion order in versions of Python before 3.6. In CPython 3.6, insertion order was preserved, but it was considered an implementation detail at that time rather than a language guarantee.

Các loại có thể gọi

Đây là các loại mà hoạt động gọi chức năng [xem phần gọi phần] có thể được áp dụng:Calls] can be applied:

Các chức năng do người dùng xác định

Một đối tượng chức năng do người dùng xác định được tạo bởi một định nghĩa hàm [xem các định nghĩa chức năng phần]. Nó nên được gọi với một danh sách đối số chứa cùng số lượng mục với danh sách tham số chính thức của hàm.Function definitions]. It should be called with an argument list containing the same number of items as the function’s formal parameter list.

Thuộc tính đặc biệt:

Thuộc tính

Nghĩa

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
07

Chuỗi tài liệu chức năng, hoặc

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
6 nếu không có sẵn; không được kế thừa bởi các lớp con.

Có thể viết

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
09

Tên chức năng tên.

Có thể viết

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
10

Tên chức năng tên.qualified name.

Chức năng tên đủ điều kiện.

Có thể viết

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
11

Tên chức năng tên.

Có thể viết

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
13

Tên chức năng tên.

Có thể viết

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
15

Tên chức năng tên.

Có thể viết

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
16

Tên chức năng tên.

Read-only

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
17

Chức năng tên đủ điều kiện.

Có thể viết

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
18

Tên chức năng tên.

Read-only

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
21

Chức năng tên đủ điều kiện.Annotations Best Practices.

Có thể viết

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
23

Tên chức năng tên.

Có thể viết

Tên chức năng tên.

Chức năng tên đủ điều kiện.

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

Tên của mô -đun hàm được xác định trong hoặc

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
6 nếu không có sẵn.

Một tuple chứa các giá trị đối số mặc định cho các đối số có mặc định hoặc
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
6 nếu không có đối số nào có giá trị mặc định.

Đối tượng mã đại diện cho cơ thể chức năng được biên dịch.

Một tham chiếu đến từ điển giữ các biến toàn cầu của hàm - không gian tên toàn cầu của mô -đun trong đó hàm được xác định.

Không gian tên hỗ trợ các thuộc tính chức năng tùy ý.

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
6 hoặc một bộ các ô chứa các liên kết cho các biến miễn phí của hàm. Xem bên dưới để biết thông tin về thuộc tính
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
20.

Khi một đối tượng Phương thức thể hiện được tạo bằng cách truy xuất đối tượng hàm do người dùng xác định từ một lớp thông qua một trong các phiên bản của nó, thuộc tính

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
27 của nó là thể hiện và đối tượng phương thức được cho là bị ràng buộc. Thuộc tính phương thức mới ____ ____128 là đối tượng hàm gốc.

Khi một đối tượng Phương thức thể hiện được tạo bằng cách truy xuất đối tượng Phương thức lớp từ một lớp hoặc phiên bản, thuộc tính

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
27 của nó là chính lớp và thuộc tính
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
28 của nó là đối tượng hàm nằm dưới phương thức lớp.

Khi một đối tượng phương thức thể hiện được gọi, hàm cơ bản [

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
28] được gọi, chèn thể hiện lớp [
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
27] trước danh sách đối số. Chẳng hạn, khi
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
41 là một lớp chứa một định nghĩa cho hàm
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
42 và
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
8 là một ví dụ của
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
41, gọi
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
45 tương đương với việc gọi
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
46.

Khi một đối tượng Phương thức thể hiện được lấy từ đối tượng Phương thức lớp, phiên bản lớp của nhóm được lưu trữ trong

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
27 sẽ thực sự là bản thân lớp, do đó, việc gọi
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
45 hoặc
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
49 tương đương với việc gọi
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
50 trong đó
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
51 là hàm phụ.

Lưu ý rằng việc chuyển đổi từ đối tượng hàm sang đối tượng phương thức thể hiện xảy ra mỗi khi thuộc tính được lấy từ thể hiện. Trong một số trường hợp, tối ưu hóa hiệu quả là gán thuộc tính cho một biến cục bộ và gọi biến cục bộ đó. Cũng lưu ý rằng việc chuyển đổi này chỉ xảy ra đối với các chức năng do người dùng xác định; Các đối tượng có thể gọi khác [và tất cả các đối tượng không thể gọi] được truy xuất mà không cần biến đổi. Cũng cần lưu ý rằng các hàm do người dùng xác định là thuộc tính của một thể hiện lớp không được chuyển đổi thành các phương thức bị ràng buộc; Điều này chỉ xảy ra khi hàm là một thuộc tính của lớp.

Chức năng máy phát điện

Một hàm hoặc phương thức sử dụng câu lệnh

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
52 [xem phần Câu lệnh Năng suất] được gọi là hàm Trình tạo. Chức năng như vậy, khi được gọi, luôn trả về một đối tượng lặp có thể được sử dụng để thực thi phần thân của hàm: gọi phương thức Iterator tựa
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
53 sẽ khiến hàm thực thi cho đến khi nó cung cấp giá trị bằng cách sử dụng câu lệnh
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
52. Khi hàm thực thi câu lệnh
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
55 hoặc rơi ra khỏi cuối, ngoại lệ
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
56 được nâng lên và trình lặp sẽ đạt đến phần cuối của tập hợp các giá trị được trả về.The yield statement] is called a generator function. Such a function, when called, always returns an iterator object which can be used to execute the body of the function: calling the iterator’s
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
53 method will cause the function to execute until it provides a value using the
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
52 statement. When the function executes a
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
55 statement or falls off the end, a
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
56 exception is raised and the iterator will have reached the end of the set of values to be returned.

Chức năng Coroutine

Một hàm hoặc phương pháp được xác định bằng cách sử dụng

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
57 được gọi là hàm coroutine. Một chức năng như vậy, khi được gọi, trả về một đối tượng coroutine. Nó có thể chứa các biểu thức
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
58, cũng như các câu lệnh
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
59 và
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
60. Xem thêm phần đối tượng Coroutine.coroutine object. It may contain
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
58 expressions, as well as
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
59 and
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
60 statements. See also the Coroutine Objects section.

Chức năng máy phát không đồng bộ

Một hàm hoặc phương thức được xác định bằng cách sử dụng

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
57 và sử dụng câu lệnh
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
52 được gọi là hàm tạo không đồng bộ. Một chức năng như vậy, khi được gọi, trả về một đối tượng lặp không đồng bộ có thể được sử dụng trong câu lệnh
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
60 để thực thi phần thân của hàm.asynchronous iterator object which can be used in an
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
60 statement to execute the body of the function.

Gọi phương thức Iterator không đồng bộ, phương thức

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
64 sẽ trả về một sự chờ đợi khi được chờ đợi sẽ thực thi cho đến khi nó cung cấp một giá trị bằng cách sử dụng biểu thức
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
52. Khi hàm thực hiện một câu lệnh
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
55 trống hoặc rơi ra khỏi cuối, một ngoại lệ
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
67 được nâng lên và trình lặp không đồng bộ sẽ đạt đến phần cuối của tập hợp các giá trị được mang lại.awaitable which when awaited will execute until it provides a value using the
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
52 expression. When the function executes an empty
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
55 statement or falls off the end, a
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
67 exception is raised and the asynchronous iterator will have reached the end of the set of values to be yielded.

Chức năng tích hợp sẵn

Một đối tượng chức năng tích hợp là một trình bao bọc xung quanh hàm C. Ví dụ về các chức năng tích hợp là

from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
0 và
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
69 [
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
70 là một mô-đun tích hợp tiêu chuẩn]. Số và loại của các đối số được xác định bởi hàm C. Các thuộc tính chỉ đọc đặc biệt:
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
07 là chuỗi tài liệu của chức năng hoặc
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
6 nếu không có sẵn;
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
09 là tên của chức năng;
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
27 được đặt thành
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
6 [nhưng xem mục tiếp theo];
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
11 là tên của mô -đun hàm được xác định trong hoặc
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
6 nếu không có sẵn.

Phương pháp tích hợp

Đây thực sự là một sự ngụy trang khác nhau của một hàm tích hợp, lần này chứa một đối tượng được chuyển đến hàm C như một đối số bổ sung ngầm. Một ví dụ về phương pháp tích hợp là

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
78, giả sử Alist là đối tượng danh sách. Trong trường hợp này, thuộc tính chỉ đọc đặc biệt
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
27 được đặt thành đối tượng được biểu thị bởi Alist.

Các lớp học

Các lớp học có thể gọi được. Các đối tượng này thường hoạt động như các nhà máy cho các trường hợp mới của chính chúng, nhưng các biến thể có thể đối với các loại lớp ghi đè

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
80. Các đối số của cuộc gọi được chuyển đến
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
80 và, trong trường hợp điển hình, đến
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
82 để khởi tạo phiên bản mới.

Trường hợp lớp học

Các trường hợp của các lớp tùy ý có thể được gọi bằng cách xác định phương thức

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
83 trong lớp của họ.

Mô -đun

Các mô-đun là một đơn vị tổ chức cơ bản của mã Python và được tạo bởi hệ thống nhập được gọi bằng câu lệnh

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
84 hoặc bằng cách gọi các chức năng như
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
85 và tích hợp
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
86. Một đối tượng mô -đun có một không gian tên được thực hiện bởi một đối tượng từ điển [đây là từ điển được tham chiếu bởi thuộc tính
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
16 của các hàm được xác định trong mô -đun]. Tài liệu tham khảo thuộc tính được dịch thành tra cứu trong từ điển này, ví dụ:
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
88 tương đương với
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
89. Một đối tượng mô -đun không chứa đối tượng mã được sử dụng để khởi tạo mô -đun [vì nó không cần thiết sau khi khởi tạo hoàn thành].import system as invoked either by the
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
84 statement, or by calling functions such as
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
85 and built-in
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
86. A module object has a namespace implemented by a dictionary object [this is the dictionary referenced by the
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
16 attribute of functions defined in the module]. Attribute references are translated to lookups in this dictionary, e.g.,
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
88 is equivalent to
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
89. A module object does not contain the code object used to initialize the module [since it isn’t needed once the initialization is done].

Bài tập thuộc tính cập nhật từ điển không gian tên mô -đun, ví dụ:

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
90 tương đương với
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
91.

Các thuộc tính được xác định trước [có thể ghi]:

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
09

Tên mô -đun.

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
07

Chuỗi tài liệu mô -đun, hoặc

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
6 nếu không có sẵn.

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
95

Tên đường dẫn của tệp mà mô -đun được tải, nếu nó được tải từ một tệp. Thuộc tính

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
95 có thể bị thiếu đối với một số loại mô -đun, chẳng hạn như các mô -đun C được liên kết tĩnh vào trình thông dịch. Đối với các mô -đun mở rộng được tải động từ một thư viện được chia sẻ, nó là tên đường dẫn của tệp thư viện được chia sẻ.

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
21

Một từ điển chứa các chú thích biến được thu thập trong quá trình thực hiện cơ thể mô -đun. Để biết thực tiễn tốt nhất khi làm việc với

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
21, vui lòng xem các chú thích thực hành tốt nhất.variable annotations collected during module body execution. For best practices on working with
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
21, please see Annotations Best Practices.

Thuộc tính chỉ đọc đặc biệt:

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
17 là không gian tên mô-đun như một đối tượng từ điển.

Chi tiết triển khai CPYThon: Do cách CPython xóa từ điển mô -đun, từ điển mô -đun sẽ được xóa khi mô -đun rơi ra khỏi phạm vi ngay cả khi từ điển vẫn có tài liệu tham khảo trực tiếp. Để tránh điều này, hãy sao chép từ điển hoặc giữ mô -đun xung quanh trong khi sử dụng trực tiếp từ điển của nó. Because of the way CPython clears module dictionaries, the module dictionary will be cleared when the module falls out of scope even if the dictionary still has live references. To avoid this, copy the dictionary or keep the module around while using its dictionary directly.

Lớp tùy chỉnh

Các loại lớp tùy chỉnh thường được tạo bởi các định nghĩa lớp [xem các định nghĩa lớp Phần]. Một lớp có một không gian tên được thực hiện bởi một đối tượng từ điển. Tài liệu tham khảo thuộc tính lớp được dịch thành tra cứu trong từ điển này, ví dụ:

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
00 được dịch thành
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
01 [mặc dù có một số móc cho phép các phương tiện định vị thuộc tính khác]. Khi tên thuộc tính không được tìm thấy ở đó, tìm kiếm thuộc tính tiếp tục trong các lớp cơ sở. Tìm kiếm các lớp cơ sở này sử dụng thứ tự độ phân giải phương pháp C3, hoạt động chính xác ngay cả khi có sự hiện diện của các cấu trúc di truyền ‘kim cương, nơi có nhiều đường di truyền dẫn trở lại tổ tiên chung. Có thể tìm thấy chi tiết bổ sung về C3 MRO được Python sử dụng trong tài liệu kèm theo bản phát hành 2.3 tại //www.python.org/doad/releases/2.3/mro/.Class definitions]. A class has a namespace implemented by a dictionary object. Class attribute references are translated to lookups in this dictionary, e.g.,
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
00 is translated to
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
01 [although there are a number of hooks which allow for other means of locating attributes]. When the attribute name is not found there, the attribute search continues in the base classes. This search of the base classes uses the C3 method resolution order which behaves correctly even in the presence of ‘diamond’ inheritance structures where there are multiple inheritance paths leading back to a common ancestor. Additional details on the C3 MRO used by Python can be found in the documentation accompanying the 2.3 release at //www.python.org/download/releases/2.3/mro/.

Khi tham chiếu thuộc tính lớp [đối với lớp

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
41, giả sử] sẽ mang lại một đối tượng phương thức lớp, nó sẽ được chuyển thành một đối tượng Phương thức thể hiện có thuộc tính
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
27 là
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
41. Khi nó mang lại một đối tượng phương thức tĩnh, nó được chuyển thành đối tượng được bọc bởi đối tượng Phương thức tĩnh. Xem phần Thực hiện các mô tả cho một cách khác trong đó các thuộc tính được lấy từ một lớp có thể khác với các thuộc tính thực sự có trong
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
17 của nó.Implementing Descriptors for another way in which attributes retrieved from a class may differ from those actually contained in its
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
17.

Bài tập thuộc tính lớp cập nhật từ điển lớp, không bao giờ là từ điển của một lớp cơ sở.

Một đối tượng lớp có thể được gọi [xem ở trên] để mang lại một thể hiện lớp [xem bên dưới].

Thuộc tính đặc biệt:

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
09

Tên lớp.

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
11

Tên của mô -đun trong đó lớp được xác định.

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
17

Từ điển chứa không gian tên lớp.

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
09

Một tuple chứa các lớp cơ sở, theo thứ tự xảy ra trong danh sách lớp cơ sở.

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
07

Chuỗi tài liệu lớp, hoặc

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
6 nếu không xác định.

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
21

Một từ điển chứa các chú thích thay đổi được thu thập trong quá trình thực hiện cơ thể lớp. Để biết thực tiễn tốt nhất khi làm việc với

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
21, vui lòng xem các chú thích thực hành tốt nhất.variable annotations collected during class body execution. For best practices on working with
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
21, please see Annotations Best Practices.

Trường hợp lớp học

Một thể hiện lớp được tạo bằng cách gọi một đối tượng lớp [xem ở trên]. Một thể hiện lớp có một không gian tên được thực hiện như một từ điển là nơi đầu tiên trong đó các tài liệu tham khảo thuộc tính được tìm kiếm. Khi một thuộc tính không được tìm thấy ở đó và lớp thể hiện có một thuộc tính theo tên đó, tìm kiếm tiếp tục với các thuộc tính của lớp. Nếu một thuộc tính lớp được tìm thấy là đối tượng hàm do người dùng xác định, nó sẽ được chuyển thành một đối tượng Phương thức thể hiện có thuộc tính

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
27 là thể hiện. Phương pháp tĩnh và các đối tượng phương pháp lớp cũng được chuyển đổi; Xem ở trên trong các lớp học của nhóm. Xem phần Thực hiện các mô tả theo cách khác trong đó các thuộc tính của một lớp được truy xuất thông qua các trường hợp của nó có thể khác với các đối tượng thực sự được lưu trữ trong lớp
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
17. Nếu không tìm thấy thuộc tính lớp nào và lớp đối tượng có phương thức
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
16, được gọi là để thỏa mãn tra cứu.Implementing Descriptors for another way in which attributes of a class retrieved via its instances may differ from the objects actually stored in the class’s
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
17. If no class attribute is found, and the object’s class has a
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
16 method, that is called to satisfy the lookup.

Bài tập thuộc tính và xóa cập nhật từ điển phiên bản, không bao giờ là từ điển lớp. Nếu lớp có phương thức

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
17 hoặc
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
18, thì điều này được gọi thay vì cập nhật trực tiếp từ điển phiên bản.

Các trường hợp lớp có thể giả vờ là số, trình tự hoặc ánh xạ nếu chúng có các phương thức với một số tên đặc biệt. Xem phần Tên phương thức đặc biệt.Special method names.

Các thuộc tính đặc biệt:

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
17 là từ điển thuộc tính;
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
20 là lớp thể hiện.

Đối tượng I/O [còn được gọi là đối tượng tệp]

Một đối tượng tệp đại diện cho một tệp mở. Các phím tắt khác nhau có sẵn để tạo các đối tượng tệp: hàm tích hợp

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
21 và cả
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
22,
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
23 và phương thức
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
24 của các đối tượng ổ cắm [và có lẽ bởi các chức năng hoặc phương thức khác được cung cấp bởi các mô-đun mở rộng].file object represents an open file. Various shortcuts are available to create file objects: the
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
21 built-in function, and also
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
22,
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
23, and the
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
24 method of socket objects [and perhaps by other functions or methods provided by extension modules].

Các đối tượng

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
25,
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
26 và
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
27 được khởi tạo vào các đối tượng tệp tương ứng với các luồng đầu vào, đầu ra và lỗi tiêu chuẩn của trình thông dịch; Tất cả đều được mở trong chế độ văn bản và do đó làm theo giao diện được xác định bởi lớp trừu tượng
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
28.

Các loại nội bộ

Một vài loại được sử dụng trong nội bộ bởi người phiên dịch được tiếp xúc với người dùng. Định nghĩa của họ có thể thay đổi với các phiên bản trong tương lai của thông dịch viên, nhưng chúng được đề cập ở đây để hoàn thiện.

Đối tượng mã

Các đối tượng mã đại diện cho mã Python thực thi Byte hoặc mã byte. Sự khác biệt giữa đối tượng mã và đối tượng hàm là đối tượng hàm chứa một tham chiếu rõ ràng đến hàm toàn cầu của hàm [mô -đun được xác định], trong khi một đối tượng mã không chứa bối cảnh; Ngoài ra, các giá trị đối số mặc định được lưu trữ trong đối tượng hàm, không phải trong đối tượng mã [vì chúng đại diện cho các giá trị được tính toán tại thời gian chạy]. Không giống như các đối tượng chức năng, các đối tượng mã là bất biến và không chứa tài liệu tham khảo [trực tiếp hoặc gián tiếp] cho các đối tượng có thể thay đổi.bytecode. The difference between a code object and a function object is that the function object contains an explicit reference to the function’s globals [the module in which it was defined], while a code object contains no context; also the default argument values are stored in the function object, not in the code object [because they represent values calculated at run-time]. Unlike function objects, code objects are immutable and contain no references [directly or indirectly] to mutable objects.

Các thuộc tính chỉ đọc đặc biệt:

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
29 cho tên hàm;
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
30 cho tên chức năng đủ điều kiện;
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
31 là tổng số đối số vị trí [bao gồm các đối số và đối số chỉ có vị trí với các giá trị mặc định];
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
32 là số lượng đối số chỉ có vị trí [bao gồm các đối số có giá trị mặc định];
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
33 là số lượng đối số chỉ từ khóa [bao gồm các đối số có giá trị mặc định];
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
34 là số biến cục bộ được sử dụng bởi hàm [bao gồm cả đối số];
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
35 là một tuple chứa tên của các biến cục bộ [bắt đầu bằng tên đối số];
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
36 là một tuple chứa tên của các biến cục bộ được tham chiếu bởi các hàm lồng nhau;
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
37 là một tuple chứa tên của các biến miễn phí;
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
38 là một chuỗi đại diện cho chuỗi các hướng dẫn mã byte;
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
39 là một tuple chứa các chữ được sử dụng bởi mã byte;
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
40 là một tuple chứa các tên được sử dụng bởi mã byte;
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
41 là tên tệp mà mã được biên dịch;
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
42 là số dòng đầu tiên của hàm;
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
43 là một chuỗi mã hóa ánh xạ từ mã ByteCode đến số dòng [để biết chi tiết, xem mã nguồn của trình thông dịch];
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
44 là kích thước ngăn xếp cần thiết;
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
45 là một số nguyên mã hóa một số cờ cho trình thông dịch.

Các bit cờ sau đây được xác định cho

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
45: bit
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
47 được đặt nếu hàm sử dụng cú pháp
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
48 để chấp nhận số lượng đối số vị trí tùy ý; bit
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
49 được đặt nếu hàm sử dụng cú pháp
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
50 để chấp nhận các đối số từ khóa tùy ý; bit
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
51 được đặt nếu hàm là trình tạo.

Khai báo tính năng trong tương lai [

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
52] cũng sử dụng các bit trong
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
45 để cho biết liệu một đối tượng mã có được biên dịch với một tính năng cụ thể được bật: BIT
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
54 được đặt hay không nếu hàm được biên dịch với bật bộ phận trong tương lai; Các bit
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
55 và
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
56 đã được sử dụng trong các phiên bản trước của Python.

Các bit khác trong

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
45 được dành riêng cho sử dụng nội bộ.

Nếu một đối tượng mã biểu thị hàm, mục đầu tiên trong

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
39 là chuỗi tài liệu của hàm hoặc
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
6 nếu không xác định.

codeObject.co_poseitions [] ¶co_positions[]

Trả về một số lượng khác nhau trên các vị trí mã nguồn của mỗi lệnh bytecode trong đối tượng mã.

Trình lặp trả về các bộ dữ liệu chứa

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
60. Tuple thứ i tương ứng với vị trí của mã nguồn được biên dịch theo lệnh thứ i. Thông tin cột là các byte UTF-8 được chỉ số 0 trên dòng nguồn đã cho.

Thông tin vị trí này có thể bị thiếu. Một danh sách không có thẩm quyền của các trường hợp có thể xảy ra:

  • Chạy trình thông dịch với

    class Philosopher:
        def __init_subclass__[cls, /, default_name, **kwargs]:
            super[].__init_subclass__[**kwargs]
            cls.default_name = default_name
    
    class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
        pass
    
    61
    class Philosopher:
        def __init_subclass__[cls, /, default_name, **kwargs]:
            super[].__init_subclass__[**kwargs]
            cls.default_name = default_name
    
    class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
        pass
    
    62.

  • Tải một tệp PYC được biên dịch trong khi sử dụng

    class Philosopher:
        def __init_subclass__[cls, /, default_name, **kwargs]:
            super[].__init_subclass__[**kwargs]
            cls.default_name = default_name
    
    class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
        pass
    
    61
    class Philosopher:
        def __init_subclass__[cls, /, default_name, **kwargs]:
            super[].__init_subclass__[**kwargs]
            cls.default_name = default_name
    
    class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
        pass
    
    62.

  • Các bộ đếm vị trí tương ứng với hướng dẫn nhân tạo.

  • Các số dòng và cột có thể được biểu diễn do các giới hạn cụ thể thực hiện.

Khi điều này xảy ra, một số hoặc tất cả các yếu tố tuple có thể là

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
6.

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

Ghi chú

Tính năng này yêu cầu lưu trữ các vị trí cột trong các đối tượng mã có thể dẫn đến sự gia tăng nhỏ sử dụng đĩa của các tệp python được biên dịch hoặc sử dụng bộ nhớ phiên dịch. Để tránh lưu trữ thông tin bổ sung và/hoặc hủy kích hoạt việc in thông tin theo dõi thêm, có thể sử dụng cờ dòng lệnh

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
61
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
62 hoặc biến môi trường
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
68 có thể được sử dụng.
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
68 environment variable can be used.

Đối tượng khung

Đối tượng khung biểu thị khung thực thi. Chúng có thể xảy ra trong các đối tượng Traceback [xem bên dưới] và cũng được chuyển sang các chức năng theo dõi đã đăng ký.

Các thuộc tính chỉ đọc đặc biệt:

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
69 là khung ngăn xếp trước đó [đối với người gọi] hoặc
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
6 nếu đây là khung ngăn xếp dưới cùng;
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
71 là đối tượng mã được thực thi trong khung này;
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
72 là từ điển được sử dụng để tra cứu các biến cục bộ;
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
73 được sử dụng cho các biến toàn cầu;
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
74 được sử dụng cho tên tích hợp [nội tại];
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
75 đưa ra lệnh chính xác [đây là một chỉ mục vào chuỗi mã byte của đối tượng mã].

Truy cập

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
71 làm tăng một sự kiện kiểm toán
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
77 với các đối số
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
78 và
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
79.auditing event
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
77 with arguments
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
78 and
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
79.

Các thuộc tính có thể ghi đặc biệt:

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
80, nếu không phải
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
6, là một hàm được gọi cho các sự kiện khác nhau trong quá trình thực thi mã [điều này được sử dụng bởi trình gỡ lỗi]. Thông thường, một sự kiện được kích hoạt cho từng dòng nguồn mới - điều này có thể được vô hiệu hóa bằng cách đặt
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
82 thành
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
9.

Việc triển khai có thể cho phép các sự kiện per-opcode được yêu cầu bằng cách đặt

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
84 thành
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
0. Lưu ý rằng điều này có thể dẫn đến hành vi thông dịch viên không xác định nếu các ngoại lệ được đưa ra bởi chức năng theo dõi thoát ra chức năng được theo dõi.

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
86 là số dòng hiện tại của khung-ghi vào số này từ bên trong hàm theo dõi nhảy vào dòng đã cho [chỉ cho khung dưới cùng nhất]. Trình gỡ lỗi có thể thực hiện lệnh Jump [hay còn gọi là câu lệnh tiếp theo] bằng cách viết cho f_lineno.

Đối tượng khung hỗ trợ một phương thức:

frame.clear []clear[]

Phương pháp này xóa tất cả các tham chiếu đến các biến cục bộ được giữ bởi khung. Ngoài ra, nếu khung thuộc về một máy phát, trình tạo được hoàn thiện. Điều này giúp phá vỡ các chu kỳ tham chiếu liên quan đến các đối tượng khung [ví dụ: khi bắt một ngoại lệ và lưu trữ dấu vết của nó để sử dụng sau].

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
87 được nâng lên nếu khung hiện đang thực hiện.

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

Đối tượng Traceback

Các đối tượng Traceback đại diện cho một dấu vết của một ngoại lệ. Một đối tượng TraceBack được tạo ngầm khi xảy ra ngoại lệ và cũng có thể được tạo rõ ràng bằng cách gọi

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
88.

Đối với các tracback được tạo ngầm, khi việc tìm kiếm một trình xử lý ngoại lệ thư giãn ngăn xếp thực thi, ở mỗi cấp độ không ngừng, một đối tượng tracback được chèn trước dấu vết hiện tại. Khi một trình xử lý ngoại lệ được nhập, dấu vết ngăn xếp được cung cấp cho chương trình. .The try statement.] It is accessible as the third item of the tuple returned by

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
89, and as the
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
90 attribute of the caught exception.

Khi chương trình không chứa trình xử lý phù hợp, dấu vết ngăn xếp được viết [được định dạng độc đáo] vào luồng lỗi tiêu chuẩn; Nếu trình thông dịch tương tác, nó cũng được cung cấp cho người dùng là

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
91.

Đối với Tracebacks được tạo rõ ràng, tùy thuộc vào người tạo ra dấu vết để xác định cách các thuộc tính

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
92 nên được liên kết để tạo thành một dấu vết ngăn xếp đầy đủ.

Các thuộc tính chỉ đọc đặc biệt:

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
93 trỏ vào khung thực thi của cấp độ hiện tại;
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
94 đưa ra số dòng nơi xảy ra ngoại lệ;
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
95 chỉ ra hướng dẫn chính xác. Số dòng và hướng dẫn cuối cùng trong TraceBack có thể khác với số dòng của đối tượng khung của nó nếu ngoại lệ xảy ra trong câu lệnh
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
1 không có khớp ngoại trừ mệnh đề hoặc với mệnh đề cuối cùng.

Truy cập

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
93 làm tăng một sự kiện kiểm toán
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
77 với các đối số
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
78 và
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
00.auditing event
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
77 with arguments
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
78 and
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
00.

Thuộc tính có thể ghi đặc biệt:

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
92 là cấp độ tiếp theo trong dấu vết ngăn xếp [về phía khung hình xảy ra ngoại lệ] hoặc
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
6 nếu không có cấp độ tiếp theo.

Đã thay đổi trong phiên bản 3.7: Các đối tượng Traceback hiện có thể được khởi tạo rõ ràng từ mã Python và thuộc tính

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
92 của các trường hợp hiện tại có thể được cập nhật.Traceback objects can now be explicitly instantiated from Python code, and the
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
92 attribute of existing instances can be updated.

Các đối tượng cắt lát

Các đối tượng lát cắt được sử dụng để biểu diễn các lát cho các phương thức

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
04. Chúng cũng được tạo bởi chức năng
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
05 tích hợp.

Các thuộc tính chỉ đọc đặc biệt:

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
06 là giới hạn dưới;
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
07 là giới hạn trên;
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
08 là giá trị bước; Mỗi là
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
6 nếu bị bỏ qua. Các thuộc tính này có thể có bất kỳ loại.

Đối tượng cắt hỗ trợ một phương pháp:

Slice.indices [bản thân, chiều dài] ¶indices[self, length]

Phương pháp này có một độ dài đối số số nguyên duy nhất và tính toán thông tin về lát cắt mà đối tượng lát cắt sẽ mô tả nếu được áp dụng cho một chuỗi các mục dài. Nó trả lại một bộ ba số nguyên; tương ứng đây là các chỉ số bắt đầu và dừng và bước hoặc độ dài sải chân của lát cắt. Các chỉ số thiếu hoặc ngoài giới hạn được xử lý theo cách phù hợp với các lát cắt thông thường.

Đối tượng phương pháp tĩnh

Các đối tượng phương thức tĩnh cung cấp một cách đánh bại việc chuyển đổi các đối tượng hàm thành các đối tượng phương thức được mô tả ở trên. Đối tượng Phương thức tĩnh là một trình bao bọc xung quanh bất kỳ đối tượng nào khác, thường là đối tượng phương thức do người dùng xác định. Khi một đối tượng Phương thức tĩnh được lấy từ một lớp hoặc một thể hiện lớp, đối tượng thực sự được trả về là đối tượng được bọc, không phải chịu bất kỳ chuyển đổi nào nữa. Các đối tượng phương thức tĩnh cũng có thể gọi được. Các đối tượng phương thức tĩnh được tạo bởi hàm tạo

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
10 tích hợp.

Đối tượng phương thức lớp

Một đối tượng phương thức lớp, giống như một đối tượng phương thức tĩnh, là một trình bao bọc xung quanh một đối tượng khác làm thay đổi cách mà đối tượng đó được lấy từ các lớp và các trường hợp lớp. Hành vi của các đối tượng phương thức lớp khi truy xuất như vậy được mô tả ở trên, theo các phương thức do người dùng định nghĩa. Các đối tượng phương thức lớp được tạo bởi hàm tạo

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
11 tích hợp.

3.3. Tên phương pháp đặc biệtSpecial method names¶

Một lớp có thể thực hiện các hoạt động nhất định được gọi bằng cú pháp đặc biệt [như các hoạt động số học hoặc đăng ký và cắt] bằng cách xác định các phương thức với các tên đặc biệt. Đây là cách tiếp cận của Python, đối với quá tải nhà điều hành, cho phép các lớp xác định hành vi của chính họ đối với các nhà khai thác ngôn ngữ. Chẳng hạn, nếu một lớp xác định một phương thức có tên

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
04 và
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
8 là một ví dụ của lớp này, thì
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
14 gần tương đương với
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
15. Ngoại trừ khi được đề cập, các nỗ lực thực hiện một thao tác nâng cao ngoại lệ khi không có phương thức thích hợp nào được xác định [thường là
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
16 hoặc
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
0].

Đặt một phương thức đặc biệt thành

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
6 chỉ ra rằng hoạt động tương ứng không có sẵn. Ví dụ: nếu một lớp đặt
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
19 thành
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
6, thì lớp không thể sử dụng được, vì vậy gọi
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
21 trên các trường hợp của nó sẽ tăng
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
0 [mà không rơi trở lại
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
04]. 2

Khi thực hiện một lớp mô phỏng bất kỳ loại tích hợp nào, điều quan trọng là việc mô phỏng chỉ được thực hiện ở mức độ có ý nghĩa đối với đối tượng được mô hình hóa. Ví dụ, một số trình tự có thể hoạt động tốt với việc truy xuất các yếu tố riêng lẻ, nhưng trích xuất một lát cắt có thể không có ý nghĩa. [Một ví dụ về điều này là giao diện

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
24 trong mô hình đối tượng tài liệu W3C.]

3.3.1. Tùy chỉnh cơ bảnBasic customization¶

Đối tượng .__ Mới __ [cls [, ...]] ¶__new__[cls[, ...]]

Được gọi để tạo một thể hiện mới của CLS lớp.

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
80 là một phương thức tĩnh [được giới thiệu đặc biệt, vì vậy bạn không cần phải khai báo nó như vậy] lấy lớp mà một thể hiện được yêu cầu làm đối số đầu tiên của nó. Các đối số còn lại là các đối số được truyền đến biểu thức hàm tạo đối tượng [cuộc gọi đến lớp]. Giá trị trả về của
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
80 phải là thể hiện đối tượng mới [thường là một thể hiện của CLS].

Các triển khai điển hình tạo ra một thể hiện mới của lớp bằng cách gọi phương thức siêu lớp ____ ____180 bằng cách sử dụng

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
28 với các đối số thích hợp và sau đó sửa đổi thể hiện mới được tạo khi cần thiết trước khi trả lại.

Nếu

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
80 được gọi trong quá trình xây dựng đối tượng và nó sẽ trả về một ví dụ của CLS, thì phương pháp phiên bản mới ____ ____182 sẽ được gọi như
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
31, trong đó bản thân là ví dụ mới và các đối số còn lại giống như được truyền cho bộ xây dựng đối tượng.

Nếu

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
80 không trả về một thể hiện của CLS, thì phương thức phiên bản mới ____ ____182 sẽ không được gọi.

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
80 được dự định chủ yếu để cho phép các lớp con của các loại bất biến [như int, str hoặc tuple] để tùy chỉnh việc tạo thể hiện. Nó cũng thường được ghi đè trong các metaclass tùy chỉnh để tùy chỉnh tạo lớp.

đối tượng .__ init __ [tự [, ...]] ¶__init__[self[, ...]]

Được gọi sau khi ví dụ đã được tạo ra [bởi

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
80], nhưng trước khi nó được trả lại cho người gọi. Các đối số là những đối số được truyền đến biểu thức trình xây dựng lớp. Nếu một lớp cơ sở có phương thức
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
82, phương thức loại Derive ____ ____182, nếu có, phải gọi rõ ràng nó để đảm bảo khởi tạo đúng phần cơ sở của phiên bản; Ví dụ:
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
38.

Bởi vì

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
80 và
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
82 hợp tác với nhau trong việc xây dựng các đối tượng [
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
80 để tạo nó và
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
82 để tùy chỉnh nó], không có giá trị nào không phải là
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
82; Làm như vậy sẽ khiến
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
0 được nâng lên trong thời gian chạy.

Đối tượng .__ Del __ [tự] ¶__del__[self]

Được gọi khi trường hợp sắp bị phá hủy. Đây cũng được gọi là một bộ hoàn cảnh hoặc [không đúng] là một kẻ phá hủy. Nếu một lớp cơ sở có phương thức

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
46, phương thức loại dẫn xuất từ ​​____346, nếu có, phải gọi nó một cách rõ ràng để đảm bảo xóa đúng phần lớp cơ sở của phiên bản.

Có thể [mặc dù không được khuyến nghị!] Đối với phương pháp

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
46 để hoãn phá hủy phiên bản bằng cách tạo một tham chiếu mới cho nó. Đây được gọi là Phục sinh đối tượng. Đó là phụ thuộc vào việc thực hiện cho dù
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
46 được gọi là lần thứ hai khi một đối tượng được hồi sinh sắp bị phá hủy; Việc triển khai CPython hiện tại chỉ gọi nó một lần.CPython implementation only calls it once.

Không được đảm bảo rằng các phương thức

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
46 được gọi cho các đối tượng vẫn còn tồn tại khi trình thông dịch thoát ra.

Ghi chú

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
51 không trực tiếp gọi
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
52 - số lần giảm trước số lượng tham chiếu cho
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
8 và cái sau chỉ được gọi khi số lượng tham chiếu ____ 18 18 đạt đến 0.

Chi tiết triển khai CPYThon: Có thể cho một chu kỳ tham chiếu để ngăn chặn số lượng tham chiếu của một đối tượng không đến 0. Trong trường hợp này, chu kỳ sau đó sẽ được phát hiện và xóa bởi người thu gom rác theo chu kỳ. Một nguyên nhân phổ biến của các chu kỳ tham chiếu là khi một ngoại lệ đã bị bắt trong một biến cục bộ. Các địa phương khung hình sau đó tham khảo ngoại lệ, tham chiếu theo dõi của riêng mình, trong đó tham chiếu người dân địa phương của tất cả các khung bị bắt trong Traceback. It is possible for a reference cycle to prevent the reference count of an object from going to zero. In this case, the cycle will be later detected and deleted by the cyclic garbage collector. A common cause of reference cycles is when an exception has been caught in a local variable. The frame’s locals then reference the exception, which references its own traceback, which references the locals of all frames caught in the traceback.

Xem thêm

Tài liệu cho mô -đun

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
0.

Cảnh báo

Do các trường hợp bấp bênh theo đó các phương thức

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
46 được gọi, các ngoại lệ xảy ra trong quá trình thực hiện của chúng bị bỏ qua và thay vào đó, cảnh báo được in thành
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
27. Đặc biệt:

  • class A:
        x = C[]  # Automatically calls: x.__set_name__[A, 'x']
    
    46 có thể được gọi khi mã tùy ý được thực thi, bao gồm từ bất kỳ luồng tùy ý nào. Nếu
    class A:
        x = C[]  # Automatically calls: x.__set_name__[A, 'x']
    
    46 cần phải khóa hoặc gọi bất kỳ tài nguyên chặn nào khác, nó có thể bị bế tắc vì tài nguyên có thể đã được lấy bởi mã bị gián đoạn để thực thi
    class A:
        x = C[]  # Automatically calls: x.__set_name__[A, 'x']
    
    46.

  • class A:
        x = C[]  # Automatically calls: x.__set_name__[A, 'x']
    
    46 có thể được thực thi trong quá trình tắt phiên dịch. Do đó, các biến toàn cầu cần truy cập [bao gồm các mô -đun khác] có thể đã bị xóa hoặc đặt thành
    class A:
        x = C[]  # Automatically calls: x.__set_name__[A, 'x']
    
    6. Python đảm bảo rằng các nhóm có tên bắt đầu bằng một dấu gạch dưới bị xóa khỏi mô -đun của họ trước khi các thế giới khác bị xóa; Nếu không có tài liệu tham khảo nào khác về các thế giới như vậy tồn tại, điều này có thể giúp đảm bảo rằng các mô -đun đã nhập vẫn có sẵn tại thời điểm phương thức
    class A:
        x = C[]  # Automatically calls: x.__set_name__[A, 'x']
    
    46 được gọi.

đối tượng .__ repr __ [tự] ¶__repr__[self]

Được gọi bởi chức năng tích hợp

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
64 để tính toán biểu diễn chuỗi chính thức của một đối tượng. Nếu có thể, điều này sẽ trông giống như một biểu thức Python hợp lệ có thể được sử dụng để tạo lại một đối tượng có cùng giá trị [được đưa ra một môi trường thích hợp]. Nếu điều này là không thể, một chuỗi của mẫu
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
65 nên được trả về. Giá trị trả về phải là một đối tượng chuỗi. Nếu một lớp xác định
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
4 nhưng không phải
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
5, thì
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
4 cũng được sử dụng khi yêu cầu một chuỗi chuỗi không chính thức của các trường hợp của lớp đó.

Điều này thường được sử dụng để gỡ lỗi, vì vậy điều quan trọng là đại diện là giàu thông tin và không rõ ràng.

đối tượng .__ str __ [tự] ¶__str__[self]

Được gọi bởi

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
69 và các chức năng tích hợp
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
70 và
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
71 để tính toán biểu diễn chuỗi không chính thức hoặc có thể in độc đáo của một đối tượng. Giá trị trả về phải là một đối tượng chuỗi.string object.

Phương pháp này khác với

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
72 ở chỗ không có kỳ vọng rằng
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
5 trả về biểu thức python hợp lệ: có thể sử dụng biểu diễn thuận tiện hơn hoặc súc tích hơn.

Việc triển khai mặc định được xác định bởi loại

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
74 được tích hợp
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
72.

đối tượng .__ byte __ [tự] ¶__bytes__[self]

Được gọi bởi byte để tính toán một biểu diễn chuỗi byte của một đối tượng. Điều này sẽ trả về một đối tượng

>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

0.bytes to compute a byte-string representation of an object. This should return a
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

0 object.

Đối tượng .__ Định dạng __ [self, format_spec] ¶__format__[self, format_spec]

Được gọi bởi chức năng tích hợp

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
70 và bằng cách mở rộng, đánh giá các chữ cái được định dạng và phương pháp
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
78, để tạo ra một biểu diễn chuỗi được định dạng của một đối tượng. Đối số Format_Spec là một chuỗi chứa mô tả về các tùy chọn định dạng mong muốn. Việc giải thích đối số format_spec tùy thuộc vào loại thực hiện
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
79, tuy nhiên hầu hết các lớp sẽ ủy thác định dạng cho một trong các loại tích hợp hoặc sử dụng cú pháp tùy chọn định dạng tương tự.formatted string literals and the
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
78 method, to produce a “formatted” string representation of an object. The format_spec argument is a string that contains a description of the formatting options desired. The interpretation of the format_spec argument is up to the type implementing
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
79, however most classes will either delegate formatting to one of the built-in types, or use a similar formatting option syntax.

Xem Đặc điểm kỹ thuật của ngôn ngữ nhỏ để biết mô tả về cú pháp định dạng tiêu chuẩn.Format Specification Mini-Language for a description of the standard formatting syntax.

Giá trị trả về phải là một đối tượng chuỗi.

Đã thay đổi trong phiên bản 3.4: Phương thức __format__ của

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
74 tự tăng
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
0 nếu được thông qua bất kỳ chuỗi không trống nào.The __format__ method of
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
74 itself raises a
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
0 if passed any non-empty string.

Đã thay đổi trong phiên bản 3.7:

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
82 hiện tương đương với
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
83 thay vì
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
84.
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
82 is now equivalent to
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
83 rather than
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
84.

đối tượng .__ lt __ [tự, khác] ¶ Đối tượng .__ le __ [tự, khác] ¶ đối tượng .__ eq __ [tự, khác] ¶ Đối tượng .__ ne __ [tự, khác] Đối tượng .__ gt __ , khác]¶__lt__[self, other]object.__le__[self, other]object.__eq__[self, other]object.__ne__[self, other]object.__gt__[self, other]object.__ge__[self, other]

Đây là những phương pháp được gọi là so sánh phong phú. Sự tương ứng giữa các ký hiệu toán tử và tên phương thức như sau:

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
85 gọi
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
86,
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
87 Các cuộc gọi
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
88,
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
89 Các cuộc gọi
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
90,
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
91 CALL
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
92,
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
93

Một phương pháp so sánh phong phú có thể trả về singleton

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
7 nếu nó không thực hiện hoạt động cho một cặp đối số nhất định. Theo quy ước,
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
9 và
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
0 được trả lại để so sánh thành công. Tuy nhiên, các phương thức này có thể trả về bất kỳ giá trị nào, vì vậy nếu toán tử so sánh được sử dụng trong bối cảnh boolean [ví dụ: trong điều kiện của câu lệnh
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
00], Python sẽ gọi
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
01 theo giá trị để xác định xem kết quả là đúng hay sai.

Theo mặc định,

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
74 thực hiện
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
03 bằng cách sử dụng
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
5, trả về
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
7 trong trường hợp so sánh sai:
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
06. Đối với
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
07, theo mặc định, nó giao cho
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
03 và đảo ngược kết quả trừ khi đó là
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
7. Không có mối quan hệ ngụ ý nào khác giữa các nhà khai thác so sánh hoặc triển khai mặc định; Ví dụ, sự thật của
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
10 không ngụ ý
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
87. Để tự động tạo các hoạt động đặt hàng từ một thao tác gốc duy nhất, xem
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
12.

Xem đoạn văn trên

class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
13 để biết một số ghi chú quan trọng về việc tạo các đối tượng có thể hỗ trợ các hoạt động so sánh tùy chỉnh và có thể sử dụng làm khóa từ điển.hashable objects which support custom comparison operations and are usable as dictionary keys.

Không có phiên bản Sang sơ đồ hoán đổi của các phương thức này [sẽ được sử dụng khi đối số bên trái không hỗ trợ hoạt động nhưng đối số bên phải có]; Thay vào đó,

class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
14 và
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
15 là sự phản ánh của nhau,
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
16 và
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
17 là sự phản ánh của nhau, và
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
03 và
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
07 là sự phản ánh của chính họ. Nếu các toán hạng thuộc các loại khác nhau và loại toán hạng bên phải là một lớp con trực tiếp hoặc gián tiếp của loại toán hạng bên trái, phương pháp được phản ánh của toán hạng bên phải được ưu tiên, nếu không phương pháp toán hạng bên trái được ưu tiên. Phân lớp ảo không được xem xét.

Đối tượng .__ Hash __ [tự] ¶__hash__[self]

Được gọi bởi chức năng tích hợp

class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
20 và cho các hoạt động trên các thành viên của các bộ sưu tập băm bao gồm
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
21,
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
22 và
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
23. Phương thức
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
13 sẽ trả về một số nguyên. Thuộc tính duy nhất được yêu cầu là các đối tượng so sánh bằng nhau có cùng giá trị băm; Bạn nên trộn lẫn các giá trị băm của các thành phần của đối tượng cũng đóng một phần so với các đối tượng bằng cách đóng gói chúng thành một tuple và băm tuple. Thí dụ:

def __hash__[self]:
    return hash[[self.name, self.nick, self.color]]

Ghi chú

class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
20 cắt giảm giá trị được trả về từ một đối tượng tùy chỉnh phương thức
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
13 theo kích thước của
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
27. Đây thường là 8 byte trên các bản dựng 64 bit và 4 byte trên các bản dựng 32 bit. Nếu một đối tượng từ
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
13 phải tương tác với các bản dựng có kích thước bit khác nhau, hãy chắc chắn kiểm tra chiều rộng trên tất cả các bản dựng được hỗ trợ. Một cách dễ dàng để làm điều này là với
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
29.

Nếu một lớp không xác định phương thức

class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
03, nó cũng không nên xác định hoạt động
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
13; Nếu nó xác định
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
03 nhưng không phải
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
13, các trường hợp của nó sẽ không thể sử dụng được như các mục trong các bộ sưu tập băm. Nếu một lớp xác định các đối tượng có thể thay đổi và thực hiện phương thức
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
03, thì nó không nên thực hiện
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
13, vì việc thực hiện các bộ sưu tập có thể băm yêu cầu giá trị băm khóa là bất biến [nếu đối tượng giá trị băm thay đổi, thì nó sẽ ở trong thùng băm sai].

Các lớp do người dùng xác định có các phương thức

class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
03 và
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
13 theo mặc định; Với họ, tất cả các đối tượng so sánh không đồng đều [ngoại trừ với chính chúng] và
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
38 trả về một giá trị thích hợp sao cho
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
39 ngụ ý cả
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
40 và
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
41.

Một lớp ghi đè

class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
03 và không xác định
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
13 sẽ có
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
13 được đặt hoàn toàn thành
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
6. Khi phương thức
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
13 của một lớp là
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
6, các trường hợp của lớp sẽ tăng
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
0 thích hợp khi chương trình cố gắng lấy giá trị băm của chúng và cũng sẽ được xác định chính xác là không thể kiểm tra được khi kiểm tra
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
49.

Nếu một lớp ghi đè

class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
03 cần giữ lại việc thực hiện
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
13 từ lớp cha, trình thông dịch phải được nói điều này một cách rõ ràng bằng cách đặt
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
52.

Nếu một lớp không ghi đè

class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
03 muốn loại bỏ hỗ trợ băm, thì nó nên bao gồm
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
54 trong định nghĩa lớp. Một lớp xác định
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
13 của chính nó, tăng rõ ràng
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
0 sẽ được xác định không chính xác là có thể băm bởi một cuộc gọi
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
49.

Ghi chú

Theo mặc định, các giá trị

class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
13 của các đối tượng STR và BYTE được xử lý với một giá trị ngẫu nhiên không thể đoán trước. Mặc dù chúng vẫn không đổi trong một quá trình Python riêng lẻ, nhưng chúng không thể dự đoán được giữa các lời mời lặp đi lặp lại của Python.

Điều này nhằm cung cấp sự bảo vệ chống lại sự từ chối dịch vụ gây ra bởi các đầu vào được lựa chọn cẩn thận để khai thác hiệu suất trường hợp xấu nhất của một sự phức tạp về chế độ chính thống, O [N2]. Xem //www.ocert.org/advisories/ocert-2011-003.html để biết chi tiết.

Thay đổi giá trị băm ảnh hưởng đến thứ tự lặp của các bộ. Python chưa bao giờ đảm bảo về thứ tự này [và nó thường thay đổi giữa các bản dựng 32 bit và 64 bit].

Xem thêm

class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
59.
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
59.

Đã thay đổi trong phiên bản 3.3: Băm ngẫu nhiên được bật theo mặc định.Hash randomization is enabled by default.

đối tượng .__ bool __ [tự] ¶__bool__[self]

Được gọi để thực hiện kiểm tra giá trị sự thật và hoạt động tích hợp

class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
01; nên trả lại
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
9 hoặc
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
0. Khi phương pháp này không được xác định,
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
63 được gọi, nếu nó được xác định và đối tượng được coi là đúng nếu kết quả của nó là không khác. Nếu một lớp xác định cả
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
63 và
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
65, tất cả các trường hợp của nó đều được coi là đúng.

3.3.2. Tùy chỉnh thuộc tính truy cậpCustomizing attribute access¶

Các phương thức sau có thể được xác định để tùy chỉnh ý nghĩa của quyền truy cập thuộc tính [sử dụng, gán cho hoặc xóa

class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
66] cho các phiên bản lớp.

đối tượng .__ getattr __ [tự, tên] ¶__getattr__[self, name]

Được gọi khi truy cập thuộc tính mặc định không thành công với

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
16 [
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
68 tăng
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
16 vì tên không phải là thuộc tính thể hiện hoặc thuộc tính trong cây lớp cho
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
70; hoặc
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
71 của thuộc tính tên tăng
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
16]. Phương thức này sẽ trả về giá trị thuộc tính [được tính toán] hoặc tăng ngoại lệ
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
16.

Lưu ý rằng nếu thuộc tính được tìm thấy thông qua cơ chế bình thường,

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
16 không được gọi. . Lưu ý rằng ít nhất các biến ví dụ, bạn có thể giả mạo toàn bộ điều khiển bằng cách không chèn bất kỳ giá trị nào trong từ điển thuộc tính thể hiện [mà thay vào đó chèn chúng vào một đối tượng khác]. Xem phương thức
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
68 bên dưới để biết cách thực sự có được toàn bộ quyền kiểm soát truy cập thuộc tính.

đối tượng .__ getattribut __ [tự, tên] ¶__getattribute__[self, name]

Được gọi là vô điều kiện để thực hiện quyền truy cập thuộc tính cho các trường hợp của lớp. Nếu lớp cũng xác định

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
16, thì cái sau sẽ không được gọi trừ khi
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
68 gọi nó một cách rõ ràng hoặc tăng
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
16. Phương thức này sẽ trả về giá trị thuộc tính [được tính toán] hoặc tăng ngoại lệ
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
16. Để tránh đệ quy vô hạn trong phương thức này, việc triển khai của nó phải luôn gọi phương thức lớp cơ sở có cùng tên để truy cập bất kỳ thuộc tính nào mà nó cần, ví dụ,
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
83.

Ghi chú

Theo mặc định, các giá trị

class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
13 của các đối tượng STR và BYTE được xử lý với một giá trị ngẫu nhiên không thể đoán trước. Mặc dù chúng vẫn không đổi trong một quá trình Python riêng lẻ, nhưng chúng không thể dự đoán được giữa các lời mời lặp đi lặp lại của Python.Special method lookup.

Điều này nhằm cung cấp sự bảo vệ chống lại sự từ chối dịch vụ gây ra bởi các đầu vào được lựa chọn cẩn thận để khai thác hiệu suất trường hợp xấu nhất của một sự phức tạp về chế độ chính thống, O [N2]. Xem //www.ocert.org/advisories/ocert-2011-003.html để biết chi tiết.auditing event

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
77 with arguments
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
78 and
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
86.

Thay đổi giá trị băm ảnh hưởng đến thứ tự lặp của các bộ. Python chưa bao giờ đảm bảo về thứ tự này [và nó thường thay đổi giữa các bản dựng 32 bit và 64 bit].__setattr__[self, name, value]

Xem thêm

class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
59.

Đã thay đổi trong phiên bản 3.3: Băm ngẫu nhiên được bật theo mặc định.

đối tượng .__ bool __ [tự] ¶auditing event

class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
89 with arguments
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
78,
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
86,
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
92.

Được gọi để thực hiện kiểm tra giá trị sự thật và hoạt động tích hợp
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
01; nên trả lại
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
9 hoặc
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
0. Khi phương pháp này không được xác định,
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
63 được gọi, nếu nó được xác định và đối tượng được coi là đúng nếu kết quả của nó là không khác. Nếu một lớp xác định cả
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
63 và
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
65, tất cả các trường hợp của nó đều được coi là đúng.
__delattr__[self, name]

3.3.2. Tùy chỉnh thuộc tính truy cập

Các phương thức sau có thể được xác định để tùy chỉnh ý nghĩa của quyền truy cập thuộc tính [sử dụng, gán cho hoặc xóa

class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
66] cho các phiên bản lớp.auditing event
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
95 with arguments
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
78 and
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
86.

đối tượng .__ getattr __ [tự, tên] ¶__dir__[self]

Được gọi khi truy cập thuộc tính mặc định không thành công với

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
16 [
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
68 tăng
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
16 vì tên không phải là thuộc tính thể hiện hoặc thuộc tính trong cây lớp cho
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
70; hoặc
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
71 của thuộc tính tên tăng
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
16]. Phương thức này sẽ trả về giá trị thuộc tính [được tính toán] hoặc tăng ngoại lệ
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
16.

3.3.2.1. Tùy chỉnh thuộc tính mô -đun truy cậpCustomizing module attribute access¶

Tên đặc biệt

class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
00 và
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
01 cũng có thể được sử dụng để tùy chỉnh quyền truy cập vào các thuộc tính mô -đun. Hàm
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
00 ở cấp độ mô -đun sẽ chấp nhận một đối số là tên của một thuộc tính và trả về giá trị được tính toán hoặc tăng
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
16. Nếu một thuộc tính không được tìm thấy trên một đối tượng mô -đun thông qua tra cứu bình thường, tức là
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
04, thì
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
00 sẽ được tìm kiếm trong mô -đun
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
17 trước khi tăng
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
16. Nếu tìm thấy, nó được gọi với tên thuộc tính và kết quả được trả về.

Hàm

class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
01 sẽ không chấp nhận đối số và trả về một chuỗi các chuỗi đại diện cho các tên có thể truy cập được trên mô -đun. Nếu có, hàm này sẽ ghi đè tìm kiếm
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
98 tiêu chuẩn trên một mô -đun.

Để tùy chỉnh hạt mịn hơn về hành vi mô -đun [cài đặt thuộc tính, thuộc tính, v.v.], người ta có thể đặt thuộc tính

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
20 của đối tượng mô -đun thành một lớp con là
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
11. Ví dụ:

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule

Ghi chú

Xác định mô -đun

class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
00 và cài đặt Mô -đun
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
20 chỉ ảnh hưởng đến các tra cứu được thực hiện bằng cú pháp truy cập thuộc tính - Trực tiếp truy cập các mô -đun toàn cầu [cho dù theo mã trong mô -đun hoặc thông qua tham chiếu đến từ điển mô -đun Globals Globals] không bị ảnh hưởng.

Đã thay đổi trong phiên bản 3.5: Thuộc tính mô -đun

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
20 hiện có thể ghi được.
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
20 module attribute is now writable.

Mới trong phiên bản 3.7:

class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
00 và
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
01 Thuộc tính mô -đun.
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
00 and
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
01 module attributes.

Xem thêm

PEP 562 - Mô -đun __getAttr__ và __dir__ - Module __getattr__ and __dir__

Mô tả các hàm

class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
00 và
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
01 trên các mô -đun.

3.3.2.2. Thực hiện mô tả JoImplementing Descriptors¶

Các phương thức sau chỉ được áp dụng khi một thể hiện của lớp chứa phương thức [một lớp mô tả được gọi là] xuất hiện trong một lớp chủ sở hữu [bộ mô tả phải nằm trong từ điển lớp của chủ sở hữu hoặc trong từ điển lớp cho một trong những phụ huynh của nó]. Trong các ví dụ dưới đây, thuộc tính, thuộc tính đề cập đến thuộc tính có tên là khóa của tài sản trong lớp chủ sở hữu

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
17.

Đối tượng .__ Nhận __ [bản thân, ví dụ, chủ sở hữu = Không] ¶__get__[self, instance, owner=None]

Được gọi để nhận thuộc tính của lớp chủ sở hữu [truy cập thuộc tính lớp] hoặc của một thể hiện của lớp đó [truy cập thuộc tính thể hiện]. Đối số chủ sở hữu tùy chọn là lớp chủ sở hữu, trong khi trường hợp là phiên bản mà thuộc tính được truy cập thông qua hoặc

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
6 khi thuộc tính được truy cập thông qua chủ sở hữu.

Phương thức này sẽ trả về giá trị thuộc tính được tính toán hoặc tăng ngoại lệ

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
16.

PEP 252 chỉ định rằng

class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
71 có thể gọi được với một hoặc hai đối số. Các mô tả tích hợp của Python sườn hỗ trợ đặc điểm kỹ thuật này; Tuy nhiên, có khả năng một số công cụ của bên thứ ba có mô tả yêu cầu cả hai đối số. Việc triển khai
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
68 của Python luôn luôn vượt qua cả hai đối số cho dù chúng có bắt buộc hay không.
specifies that
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
71 is callable with one or two arguments. Python’s own built-in descriptors support this specification; however, it is likely that some third-party tools have descriptors that require both arguments. Python’s own
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
68 implementation always passes in both arguments whether they are required or not.

Đối tượng .__ Đặt __ [bản thân, ví dụ, giá trị] ¶__set__[self, instance, value]

Được gọi để đặt thuộc tính trên một thể hiện của lớp chủ sở hữu thành một giá trị mới, giá trị.

Lưu ý, thêm

class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
24 hoặc
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
25 thay đổi loại mô tả thành một mô tả dữ liệu của người dùng. Xem các mô tả gọi để biết thêm chi tiết.Invoking Descriptors for more details.

đối tượng .__ Xóa __ [bản thân, ví dụ] ¶__delete__[self, instance]

Được gọi để xóa thuộc tính trên một thể hiện của lớp chủ sở hữu.

Thuộc tính

class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
26 được giải thích bởi mô -đun
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
27 khi chỉ định lớp nơi đối tượng này được xác định [đặt điều này một cách thích hợp có thể hỗ trợ trong thời gian chạy của các thuộc tính lớp động]. Đối với các thiết bị gọi, nó có thể chỉ ra rằng một thể hiện của loại đã cho [hoặc một lớp con] được mong đợi hoặc được yêu cầu là đối số vị trí đầu tiên [ví dụ, CPython đặt thuộc tính này cho các phương thức không liên kết được thực hiện trong C].

3.3.2.3. Gọi các mô tảInvoking Descriptors¶

Nói chung, một mô tả là một thuộc tính đối tượng với hành vi ràng buộc của Google, một thuộc tính có quyền truy cập thuộc tính đã bị ghi đè bởi các phương thức trong giao thức mô tả:

class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
71,
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
24 và
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
25. Nếu bất kỳ phương pháp nào được xác định cho một đối tượng, nó được cho là một mô tả.

Hành vi mặc định cho quyền truy cập thuộc tính là để có được, đặt hoặc xóa thuộc tính khỏi từ điển đối tượng. Chẳng hạn,

class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
31 có chuỗi tra cứu bắt đầu bằng
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
32, sau đó
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
33 và tiếp tục thông qua các lớp cơ sở của
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
34 không bao gồm các metaclass.

Tuy nhiên, nếu giá trị tra cứu là một đối tượng xác định một trong các phương thức mô tả, thì Python có thể ghi đè hành vi mặc định và thay vào đó gọi phương thức mô tả. Trường hợp điều này xảy ra trong chuỗi ưu tiên phụ thuộc vào phương thức mô tả nào được xác định và cách chúng được gọi.

Điểm khởi đầu cho việc gọi mô tả là một ràng buộc,

class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
31. Làm thế nào các đối số được lắp ráp tùy thuộc vào
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
8:

Gọi trực tiếp

Cuộc gọi đơn giản nhất và ít nhất là khi mã người dùng gọi trực tiếp phương thức mô tả:

class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
37.

Ví dụ ràng buộc

Nếu liên kết với một thể hiện đối tượng,

class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
31 sẽ được chuyển thành cuộc gọi:
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
39.

Ràng buộc lớp

Nếu liên kết với một lớp,

class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
40 sẽ được chuyển thành cuộc gọi:
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
41.

Siêu ràng buộc

Tra cứu chấm chấm, chẳng hạn như

class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
42 tìm kiếm
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
43 cho lớp cơ sở
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
44 sau
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
45 và sau đó trả về
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
46. Nếu không phải là một mô tả,
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
8 được trả về không thay đổi.

Ví dụ, các ràng buộc, mức độ ưu tiên của việc gọi mô tả phụ thuộc vào phương thức mô tả nào được xác định. Một mô tả có thể xác định bất kỳ sự kết hợp nào của

class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
71,
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
24 và
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
25. Nếu nó không xác định
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
71, thì việc truy cập thuộc tính sẽ trả về chính đối tượng mô tả trừ khi có một giá trị trong từ điển thể hiện đối tượng. Nếu mô tả xác định
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
24 và/hoặc
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
25, thì đó là một mô tả dữ liệu; Nếu nó không định nghĩa, đó là một mô tả không phải là dữ liệu. Thông thường, các mô tả dữ liệu xác định cả
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
71 và
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
24, trong khi các mô tả không phải là dữ liệu chỉ có phương pháp
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
71. Các mô tả dữ liệu với
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
71 và
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
24 [và/hoặc
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
25] được xác định luôn ghi đè một định nghĩa lại trong một từ điển thể hiện. Ngược lại, các mô tả phi dữ liệu có thể bị ghi đè bởi các trường hợp.

Các phương pháp Python [bao gồm cả các phương pháp được trang trí bằng

class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
60 và
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
61] được thực hiện dưới dạng mô tả không dữ liệu. Theo đó, các trường hợp có thể xác định lại và ghi đè các phương thức. Điều này cho phép các trường hợp cá nhân có được các hành vi khác với các trường hợp khác của cùng một lớp.

Hàm

class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
62 được triển khai dưới dạng mô tả dữ liệu. Theo đó, các trường hợp không thể ghi đè hành vi của một tài sản.

3.3.2.4. __Slots__¶__slots__¶

__Slots__ cho phép chúng tôi khai báo rõ ràng các thành viên dữ liệu [như thuộc tính] và từ chối việc tạo

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
17 và __weakref__ [trừ khi được khai báo rõ ràng trong __Slots__ hoặc có sẵn trong cha mẹ.]

Không gian được lưu qua bằng cách sử dụng

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
17 có thể là đáng kể. Tốc độ tra cứu thuộc tính cũng có thể được cải thiện đáng kể là tốt.

Đối tượng .__ Slots__¶__slots__

Biến lớp này có thể được gán một chuỗi, có thể lặp lại hoặc chuỗi chuỗi với các tên biến được sử dụng bởi các trường hợp. __Slots__ Bảo lưu không gian cho các biến được khai báo và ngăn chặn việc tạo tự động

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
17 và __weakref__ cho mỗi trường hợp.

3.3.2.4.1. Ghi chú về việc sử dụng __Slots__¶Notes on using __slots__¶
  • Khi kế thừa từ một lớp không có __Slots__, thuộc tính

    import sys
    from types import ModuleType
    
    class VerboseModule[ModuleType]:
        def __repr__[self]:
            return f'Verbose {self.__name__}'
    
        def __setattr__[self, attr, value]:
            print[f'Setting {attr}...']
            super[].__setattr__[attr, value]
    
    sys.modules[__name__].__class__ = VerboseModule
    
    17 và __weakref__ của các trường hợp sẽ luôn có thể truy cập được.

  • Nếu không có biến

    import sys
    from types import ModuleType
    
    class VerboseModule[ModuleType]:
        def __repr__[self]:
            return f'Verbose {self.__name__}'
    
        def __setattr__[self, attr, value]:
            print[f'Setting {attr}...']
            super[].__setattr__[attr, value]
    
    sys.modules[__name__].__class__ = VerboseModule
    
    17, các phiên bản không thể được gán các biến mới không được liệt kê trong định nghĩa __slots__. Cố gắng gán cho một tên biến chưa niêm yết tăng
    class A:
        x = C[]  # Automatically calls: x.__set_name__[A, 'x']
    
    16. Nếu sự gán động của các biến mới là mong muốn, thì hãy thêm
    class Meta[type]:
        pass
    
    class MyClass[metaclass=Meta]:
        pass
    
    class MySubclass[MyClass]:
        pass
    
    69 vào chuỗi chuỗi trong khai báo __slots__.

  • Không có biến __weakref__ cho mỗi trường hợp, các lớp xác định __Slots__ không hỗ trợ

    class Meta[type]:
        pass
    
    class MyClass[metaclass=Meta]:
        pass
    
    class MySubclass[MyClass]:
        pass
    
    70 cho các trường hợp của nó. Nếu cần hỗ trợ tham chiếu yếu, thì hãy thêm
    class Meta[type]:
        pass
    
    class MyClass[metaclass=Meta]:
        pass
    
    class MySubclass[MyClass]:
        pass
    
    71 vào chuỗi chuỗi trong khai báo __Slots__.

  • __Slots__ được triển khai ở cấp lớp bằng cách tạo các mô tả cho từng tên biến. Do đó, các thuộc tính lớp không thể được sử dụng để đặt các giá trị mặc định cho các biến được xác định bởi __slots__; Mặt khác, thuộc tính lớp sẽ ghi đè lên gán mô tả.descriptors for each variable name. As a result, class attributes cannot be used to set default values for instance variables defined by __slots__; otherwise, the class attribute would overwrite the descriptor assignment.

  • Hành động của tuyên bố __Slots__ không giới hạn ở lớp nơi nó được xác định. __Slots__ được tuyên bố ở phụ huynh có sẵn trong các lớp con. Tuy nhiên, các lớp con của con sẽ nhận được

    import sys
    from types import ModuleType
    
    class VerboseModule[ModuleType]:
        def __repr__[self]:
            return f'Verbose {self.__name__}'
    
        def __setattr__[self, attr, value]:
            print[f'Setting {attr}...']
            super[].__setattr__[attr, value]
    
    sys.modules[__name__].__class__ = VerboseModule
    
    17 và __weakref__ trừ khi chúng cũng xác định __slots__ [chỉ nên chứa tên của bất kỳ vị trí bổ sung nào].

  • Nếu một lớp xác định một vị trí cũng được xác định trong một lớp cơ sở, thì biến thể hiện được xác định bởi khe cắm lớp cơ sở là không thể truy cập [ngoại trừ bằng cách truy xuất bộ mô tả của nó trực tiếp từ lớp cơ sở]. Điều này thể hiện ý nghĩa của chương trình không xác định. Trong tương lai, một kiểm tra có thể được thêm vào để ngăn chặn điều này.

  • __Slots__ không hoạt động không hoạt động cho các lớp có nguồn gốc từ các loại tích hợp có độ dài biến đổi của các loại khác nhau như

    class A:
       pass
    
    c = C[]
    A.x = c                  # The hook is not called
    c.__set_name__[A, 'x']   # Manually invoke the hook
    
    7,
    >>> from enum import Enum
    >>> class Menu[Enum]:
    ...     """A breakfast menu"""
    ...     SPAM = 'spam'
    ...     BACON = 'bacon'
    ...
    >>> # Enum classes have a custom metaclass:
    >>> type[Menu]
    
    >>> # EnumMeta defines __getitem__,
    >>> # so __class_getitem__ is not called,
    >>> # and the result is not a GenericAlias object:
    >>> Menu['SPAM']
    
    >>> type[Menu['SPAM']]
    
    
    0 và
    class Meta[type]:
        pass
    
    class MyClass[metaclass=Meta]:
        pass
    
    class MySubclass[MyClass]:
        pass
    
    75.

  • Bất kỳ sự khác có thể không có thể được gán cho __Slots__.iterable may be assigned to __slots__.

  • Nếu

    class Meta[type]:
        pass
    
    class MyClass[metaclass=Meta]:
        pass
    
    class MySubclass[MyClass]:
        pass
    
    76 được sử dụng để gán __Slots__, các khóa từ điển sẽ được sử dụng làm tên khe. Các giá trị của từ điển có thể được sử dụng để cung cấp các tài liệu tham gia tham gia sẽ được công nhận bởi
    class Meta[type]:
        pass
    
    class MyClass[metaclass=Meta]:
        pass
    
    class MySubclass[MyClass]:
        pass
    
    77 và được hiển thị trong đầu ra của
    class Meta[type]:
        pass
    
    class MyClass[metaclass=Meta]:
        pass
    
    class MySubclass[MyClass]:
        pass
    
    78.

  • class Philosopher:
        def __init_subclass__[cls, /, default_name, **kwargs]:
            super[].__init_subclass__[**kwargs]
            cls.default_name = default_name
    
    class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
        pass
    
    20 Bài tập chỉ hoạt động nếu cả hai lớp có cùng __Slots__.

  • Có thể sử dụng nhiều kế thừa với nhiều lớp cha mẹ có rãnh, nhưng chỉ có một phụ huynh được phép có các thuộc tính được tạo bởi các vị trí [các cơ sở khác phải có bố cục khe trống] - vi phạm tăng

    class A:
       pass
    
    c = C[]
    A.x = c                  # The hook is not called
    c.__set_name__[A, 'x']   # Manually invoke the hook
    
    0. with multiple slotted parent classes can be used, but only one parent is allowed to have attributes created by slots [the other bases must have empty slot layouts] - violations raise
    class A:
       pass
    
    c = C[]
    A.x = c                  # The hook is not called
    c.__set_name__[A, 'x']   # Manually invoke the hook
    
    0.

  • Nếu một trình lặp được sử dụng cho __Slots__ thì một mô tả được tạo cho mỗi giá trị của trình lặp. Tuy nhiên, thuộc tính __Slots__ sẽ là một trình lặp trống.iterator is used for __slots__ then a descriptor is created for each of the iterator’s values. However, the __slots__ attribute will be an empty iterator.

3.3.3. Tùy chỉnh lớp tạo lớpCustomizing class creation¶

Bất cứ khi nào một lớp kế thừa từ một lớp khác,

class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
81 được gọi trên lớp cha. Bằng cách này, có thể viết các lớp thay đổi hành vi của các lớp con. Điều này liên quan chặt chẽ đến các nhà trang trí lớp, nhưng trong đó các nhà trang trí lớp chỉ ảnh hưởng đến lớp cụ thể mà họ áp dụng,
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
82 chỉ áp dụng cho các lớp con trong tương lai của lớp xác định phương pháp.

ClassMethodObject .__ init_subClass __ [CLS] ¶object.__init_subclass__[cls]

Phương pháp này được gọi bất cứ khi nào lớp chứa được phân lớp. CLS sau đó là lớp con mới. Nếu được định nghĩa là phương thức thể hiện bình thường, phương pháp này được chuyển đổi hoàn toàn thành phương thức lớp.

Các đối số từ khóa được trao cho một lớp mới được chuyển đến lớp cha mẹ

class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
82. Để tương thích với các lớp khác bằng cách sử dụng
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
82, người ta nên lấy ra các đối số từ khóa cần thiết và chuyển các lớp khác sang lớp cơ sở, như trong:

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass

Việc triển khai mặc định

class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
85 không làm gì, nhưng sẽ gây ra lỗi nếu nó được gọi với bất kỳ đối số nào.

Ghi chú

Gợi ý Metaclass

class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
86 được tiêu thụ bởi phần còn lại của máy móc loại và không bao giờ được chuyển sang triển khai
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
82. Metaclass thực tế [chứ không phải là gợi ý rõ ràng] có thể được truy cập là
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
88.

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

Khi một lớp được tạo,

class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
89 quét các biến lớp và thực hiện các cuộc gọi lại cho những biến có móc
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
90.

đối tượng .__ set_name __ [tự, chủ sở hữu, tên] ¶__set_name__[self, owner, name]

Tự động gọi vào thời điểm chủ sở hữu lớp sở hữu được tạo. Đối tượng đã được gán cho tên trong lớp đó:

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']

Nếu biến lớp được gán sau khi lớp được tạo,

class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
90 sẽ không được gọi tự động. Nếu cần,
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
90 có thể được gọi trực tiếp:

class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook

Xem Tạo đối tượng lớp để biết thêm chi tiết.Creating the class object for more details.

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

Khi một lớp được tạo,
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
89 quét các biến lớp và thực hiện các cuộc gọi lại cho những biến có móc
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
90.
Metaclasses¶

đối tượng .__ set_name __ [tự, chủ sở hữu, tên] ¶

Tự động gọi vào thời điểm chủ sở hữu lớp sở hữu được tạo. Đối tượng đã được gán cho tên trong lớp đó:

Nếu biến lớp được gán sau khi lớp được tạo,

class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
90 sẽ không được gọi tự động. Nếu cần,
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
90 có thể được gọi trực tiếp:

Xem Tạo đối tượng lớp để biết thêm chi tiết.

3.3.3.1. Metaclasses¶

  • Theo mặc định, các lớp được xây dựng bằng

    import sys
    from types import ModuleType
    
    class VerboseModule[ModuleType]:
        def __repr__[self]:
            return f'Verbose {self.__name__}'
    
        def __setattr__[self, attr, value]:
            print[f'Setting {attr}...']
            super[].__setattr__[attr, value]
    
    sys.modules[__name__].__class__ = VerboseModule
    
    9. Cơ thể lớp được thực hiện trong một không gian tên mới và tên lớp bị ràng buộc cục bộ với kết quả của
    class Meta[type]:
        pass
    
    class MyClass[metaclass=Meta]:
        pass
    
    class MySubclass[MyClass]:
        pass
    
    94.

  • Quá trình tạo lớp có thể được tùy chỉnh bằng cách truyền đối số từ khóa

    class Meta[type]:
        pass
    
    class MyClass[metaclass=Meta]:
        pass
    
    class MySubclass[MyClass]:
        pass
    
    86 trong dòng định nghĩa lớp hoặc bằng cách kế thừa từ một lớp hiện có bao gồm một đối số như vậy. Trong ví dụ sau, cả
    class Meta[type]:
        pass
    
    class MyClass[metaclass=Meta]:
        pass
    
    class MySubclass[MyClass]:
        pass
    
    96 và
    class Meta[type]:
        pass
    
    class MyClass[metaclass=Meta]:
        pass
    
    class MySubclass[MyClass]:
        pass
    
    97 đều là trường hợp của
    class Meta[type]:
        pass
    
    class MyClass[metaclass=Meta]:
        pass
    
    class MySubclass[MyClass]:
        pass
    
    98:

  • class Meta[type]:
        pass
    
    class MyClass[metaclass=Meta]:
        pass
    
    class MySubclass[MyClass]:
        pass
    

  • Bất kỳ đối số từ khóa nào khác được chỉ định trong định nghĩa lớp được truyền qua tất cả các hoạt động Metaclass được mô tả dưới đây.

  • Khi một định nghĩa lớp được thực thi, các bước sau xảy ra:

Các mục MRO được giải quyết;Resolving MRO entries¶

Các metaclass thích hợp được xác định;

Không gian tên lớp được chuẩn bị;

Cơ thể lớp được thực hiện; - Core support for typing module and generic types

Đối tượng lớp được tạo.Determining the appropriate metaclass¶

3.3.3.2. Giải quyết các mục MRO

  • Nếu một cơ sở xuất hiện trong định nghĩa lớp không phải là một thể hiện của

    class Meta[type]:
        pass
    
    class MyClass[metaclass=Meta]:
        pass
    
    class MySubclass[MyClass]:
        pass
    
    99, thì một phương thức
    from inspect import isclass
    
    def subscribe[obj, x]:
        """Return the result of the expression 'obj[x]'"""
    
        class_of_obj = type[obj]
    
        # If the class of obj defines __getitem__,
        # call class_of_obj.__getitem__[obj, x]
        if hasattr[class_of_obj, '__getitem__']:
            return class_of_obj.__getitem__[obj, x]
    
        # Else, if obj is a class and defines __class_getitem__,
        # call obj.__class_getitem__[x]
        elif isclass[obj] and hasattr[obj, '__class_getitem__']:
            return obj.__class_getitem__[x]
    
        # Else, raise an exception
        else:
            raise TypeError[
                f"'{class_of_obj.__name__}' object is not subscriptable"
            ]
    
    00 được tìm kiếm trên nó. Nếu tìm thấy, nó được gọi với các cơ sở ban đầu. Phương pháp này phải trả về một bộ các lớp sẽ được sử dụng thay vì cơ sở này. Tuple có thể trống, trong trường hợp như vậy, cơ sở ban đầu bị bỏ qua.

  • Xem thêm

  • PEP 560 - Hỗ trợ cốt lõi để gõ mô -đun và loại chung

3.3.3.3. Xác định Metaclass¶ phù hợp

Metaclass thích hợp cho định nghĩa lớp được xác định như sau:Preparing the class namespace¶

Nếu không có cơ sở và không có metaclass rõ ràng được đưa ra, thì

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
9 được sử dụng;

Nếu một metaclass rõ ràng được đưa ra và nó không phải là một ví dụ của

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
9, thì nó được sử dụng trực tiếp làm metaclass;

Xem thêm

PEP 3115 - Metaclasses trong Python 3000 - Metaclasses in Python 3000

Đã giới thiệu móc tên

from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
06

3.3.3.5. Thực hiện cơ thể lớpExecuting the class body¶

Cơ thể lớp được thực thi [xấp xỉ] là

from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
15. Sự khác biệt chính từ một cuộc gọi bình thường đến
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
16 là phạm vi từ vựng cho phép cơ thể lớp [bao gồm bất kỳ phương thức nào] để tham chiếu tên từ phạm vi hiện tại và bên ngoài khi định nghĩa lớp xảy ra bên trong hàm.

Tuy nhiên, ngay cả khi định nghĩa lớp xảy ra bên trong hàm, các phương thức được xác định bên trong lớp vẫn không thể thấy tên được xác định ở phạm vi lớp. Các biến lớp phải được truy cập thông qua tham số đầu tiên của các phương thức thể hiện hoặc lớp hoặc thông qua tham chiếu

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
20 phạm vi từ vựng ngầm được mô tả trong phần tiếp theo.

3.3.3.6. Tạo đối tượng lớpCreating the class object¶

Khi không gian tên lớp đã được điền bằng cách thực thi thân lớp, đối tượng lớp được tạo bằng cách gọi

from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
18 [các từ khóa bổ sung được truyền ở đây giống như các từ được chuyển đến
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
06].

Đối tượng lớp này là một đối tượng sẽ được tham chiếu bởi hình thức không có đối số của

from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
20.
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
20 là một tham chiếu đóng ẩn được tạo bởi trình biên dịch nếu bất kỳ phương thức nào trong cơ thể lớp tham khảo
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
20 hoặc
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
23. Điều này cho phép hình thức đối số bằng không của
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
20 để xác định chính xác lớp được xác định dựa trên phạm vi từ vựng, trong khi lớp hoặc thể hiện được sử dụng để thực hiện cuộc gọi hiện tại được xác định dựa trên đối số đầu tiên được truyền vào phương thức.

Chi tiết triển khai CPYThon: Trong CPython 3.6 trở lên, tế bào

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
20 được truyền cho Metaclass dưới dạng mục
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
26 trong không gian tên lớp. Nếu có mặt, điều này phải được truyền đến cuộc gọi
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
27 để lớp được khởi tạo chính xác. Không làm như vậy sẽ dẫn đến
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
87 trong Python 3.8.
In CPython 3.6 and later, the
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
20 cell is passed to the metaclass as a
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
26 entry in the class namespace. If present, this must be propagated up to the
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
27 call in order for the class to be initialised correctly. Failing to do so will result in a
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
87 in Python 3.8.

Khi sử dụng metaclass mặc định

class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
99 hoặc bất kỳ metaclass nào cuối cùng gọi
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
27, các bước tùy chỉnh bổ sung sau đây sẽ được gọi sau khi tạo đối tượng lớp:

  1. Phương thức

    from inspect import isclass
    
    def subscribe[obj, x]:
        """Return the result of the expression 'obj[x]'"""
    
        class_of_obj = type[obj]
    
        # If the class of obj defines __getitem__,
        # call class_of_obj.__getitem__[obj, x]
        if hasattr[class_of_obj, '__getitem__']:
            return class_of_obj.__getitem__[obj, x]
    
        # Else, if obj is a class and defines __class_getitem__,
        # call obj.__class_getitem__[x]
        elif isclass[obj] and hasattr[obj, '__class_getitem__']:
            return obj.__class_getitem__[x]
    
        # Else, raise an exception
        else:
            raise TypeError[
                f"'{class_of_obj.__name__}' object is not subscriptable"
            ]
    
    27 thu thập tất cả các thuộc tính trong không gian tên lớp xác định phương thức
    class Meta[type]:
        pass
    
    class MyClass[metaclass=Meta]:
        pass
    
    class MySubclass[MyClass]:
        pass
    
    90;

  2. Các phương thức

    from inspect import isclass
    
    def subscribe[obj, x]:
        """Return the result of the expression 'obj[x]'"""
    
        class_of_obj = type[obj]
    
        # If the class of obj defines __getitem__,
        # call class_of_obj.__getitem__[obj, x]
        if hasattr[class_of_obj, '__getitem__']:
            return class_of_obj.__getitem__[obj, x]
    
        # Else, if obj is a class and defines __class_getitem__,
        # call obj.__class_getitem__[x]
        elif isclass[obj] and hasattr[obj, '__class_getitem__']:
            return obj.__class_getitem__[x]
    
        # Else, raise an exception
        else:
            raise TypeError[
                f"'{class_of_obj.__name__}' object is not subscriptable"
            ]
    
    33 được gọi với lớp được xác định và tên được gán của thuộc tính cụ thể đó;

  3. Móc

    class Meta[type]:
        pass
    
    class MyClass[metaclass=Meta]:
        pass
    
    class MySubclass[MyClass]:
        pass
    
    81 được gọi là cha mẹ ngay lập tức của lớp mới theo thứ tự phân giải phương thức.

Sau khi đối tượng lớp được tạo, nó được chuyển cho các nhà trang trí lớp được bao gồm trong định nghĩa lớp [nếu có] và đối tượng kết quả bị ràng buộc trong không gian tên cục bộ là lớp xác định.

Khi một lớp mới được tạo bởi

from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
27, đối tượng được cung cấp dưới dạng tham số không gian tên được sao chép vào ánh xạ mới được đặt hàng và đối tượng gốc bị loại bỏ. Bản sao mới được bọc trong một proxy chỉ đọc, trở thành thuộc tính
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
17 của đối tượng lớp.

Xem thêm

Pep 3135 - Super mới - New super

Mô tả tham chiếu đóng cửa

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
20 ngầm

3.3.3.7. Sử dụng cho Metaclasses¶Uses for metaclasses¶

Việc sử dụng tiềm năng cho các metaclass là vô biên. Một số ý tưởng đã được khám phá bao gồm enum, ghi nhật ký, kiểm tra giao diện, ủy quyền tự động, tạo tài sản tự động, proxy, khung và khóa/đồng bộ hóa tài nguyên tự động.

3.3.4. Tùy chỉnh phiên bản và kiểm tra lớp conCustomizing instance and subclass checks¶

Các phương thức sau được sử dụng để ghi đè hành vi mặc định của các hàm tích hợp

from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
38 và
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
39.

Cụ thể, Metaclass

from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
40 thực hiện các phương pháp này để cho phép bổ sung các lớp cơ sở trừu tượng [ABC] như các lớp cơ sở ảo của Hồi giáo vào bất kỳ loại hoặc loại nào [bao gồm cả các loại tích hợp], bao gồm cả các ABC khác.

lớp .__ InstanceCheck __ [bản thân, ví dụ] ¶__instancecheck__[self, instance]

Trả về true nếu thể hiện nên được coi là một thể hiện [trực tiếp hoặc gián tiếp] của lớp. Nếu được xác định, được gọi để thực hiện

from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
41.

Lớp .__ Classcheck __ [tự, lớp con] ¶__subclasscheck__[self, subclass]

Trả về true nếu lớp con nên được coi là một lớp con [trực tiếp hoặc gián tiếp] của lớp. Nếu được xác định, được gọi để thực hiện

from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
42.

Lưu ý rằng các phương pháp này được tra cứu trên loại [metaclass] của một lớp. Chúng không thể được định nghĩa là phương thức lớp trong lớp thực tế. Điều này phù hợp với việc tra cứu các phương pháp đặc biệt được gọi trên các trường hợp, chỉ trong trường hợp này, trường hợp đó là một lớp.

3.3.5. Mô phỏng các loại chung chungEmulating generic types¶

Khi sử dụng các chú thích loại, thường rất hữu ích khi tham số hóa một loại chung bằng cách sử dụng ký hiệu khung vuông Python. Ví dụ, chú thích

from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
43 có thể được sử dụng để biểu thị
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
44 trong đó tất cả các yếu tố thuộc loại
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
7.type annotations, it is often useful to parameterize a generic type using Python’s square-brackets notation. For example, the annotation
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
43 might be used to signify a
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
44 in which all the elements are of type
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
7.

Xem thêm

PEP 484 - Loại gợi ý - Type Hints

Giới thiệu Khung Python cho các chú thích loại

Các loại bí danh chung

Tài liệu cho các đối tượng đại diện cho các lớp chung được tham số hóa

Generics, Generics do người dùng định nghĩa và
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
46
, user-defined generics and
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
46

Tài liệu về cách thực hiện các lớp chung có thể được tham số hóa trong thời gian chạy và được hiểu bởi các trình kiểm tra loại tĩnh.

Một lớp thường chỉ có thể được tham số hóa nếu nó xác định phương thức lớp đặc biệt

from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
47.

classMethodObject .__ class_getItem __ [cls, key] ¶ object.__class_getitem__[cls, key]

Trả về một đối tượng đại diện cho chuyên môn hóa của một lớp chung theo các đối số loại được tìm thấy trong khóa.

Khi được xác định trên một lớp,

from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
47 tự động là phương thức lớp. Như vậy, không cần nó được trang trí với
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
61 khi nó được xác định.

3.3.5.1. Mục đích của __class_getitem__¶The purpose of __class_getitem__¶

Mục đích của

from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
47 là cho phép tham số hóa thời gian chạy của các lớp chung thư viện tiêu chuẩn để dễ dàng áp dụng các gợi ý loại cho các lớp này.type hints to these classes.

Để thực hiện các lớp chung tùy chỉnh có thể được tham số hóa trong thời gian chạy và được hiểu bởi các trình kiểm tra loại tĩnh, người dùng nên kế thừa từ một lớp thư viện tiêu chuẩn đã thực hiện

from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
47 hoặc kế thừa từ
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
46, có việc triển khai riêng
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
47.

Việc triển khai tùy chỉnh của

from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
47 trên các lớp được xác định bên ngoài thư viện tiêu chuẩn có thể không được hiểu bởi các trình kiểm tra loại bên thứ ba như MyPy. Sử dụng
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
47 trên bất kỳ lớp nào cho các mục đích khác ngoài gợi ý loại không được khuyến khích.

3.3.5.2. __ class_getitem__ so với __getItem__¶__class_getitem__ versus __getitem__¶

Thông thường, đăng ký của một đối tượng sử dụng dấu ngoặc vuông sẽ gọi phương thức thể hiện

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
04 được xác định trên lớp đối tượng. Tuy nhiên, nếu đối tượng được đăng ký là một lớp, phương thức lớp
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
47 có thể được gọi thay thế.
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
47 sẽ trả về một đối tượng Generalias nếu nó được xác định đúng.subscription of an object using square brackets will call the
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
04 instance method defined on the object’s class. However, if the object being subscribed is itself a class, the class method
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
47 may be called instead.
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
47 should return a GenericAlias object if it is properly defined.

Được trình bày với biểu thức

from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
59, trình thông dịch Python tuân theo một cái gì đó giống như quá trình sau để quyết định xem
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
04 hay
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
47 nên được gọi là:expression
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
59, the Python interpreter follows something like the following process to decide whether
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
04 or
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
47 should be called:

from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]

Trong Python, tất cả các lớp là trường hợp của các lớp khác. Lớp học của một lớp được gọi là lớp Metaclass của lớp, và hầu hết các lớp đều có lớp

class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
99 là metaclass của họ.
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
99 không xác định
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
04, có nghĩa là các biểu thức như
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
43,
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
66 và
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
67 đều dẫn đến
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
47 được gọi là:metaclass, and most classes have the
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
99 class as their metaclass.
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
99 does not define
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
04, meaning that expressions such as
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
43,
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
66 and
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
67 all result in
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
47 being called:

>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

Tuy nhiên, nếu một lớp có một metaclass tùy chỉnh xác định

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
04, việc đăng ký lớp có thể dẫn đến hành vi khác nhau. Một ví dụ về điều này có thể được tìm thấy trong mô -đun
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
70:

>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

3.3.6. Mô phỏng các đối tượng có thể gọi đượcEmulating callable objects¶

Đối tượng .__ Gọi __ [tự [, args ...]] ¶__call__[self[, args...]]

Được gọi là khi thể hiện là người được gọi là một chức năng; Nếu phương pháp này được xác định,

from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
71 được dịch gần như
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
72.

3.3.7. Mô phỏng các loại containerEmulating container types¶

Các phương pháp sau đây có thể được xác định để thực hiện các đối tượng container. Các container thường là các chuỗi [như

from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
73 hoặc
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
74] hoặc ánh xạ [như
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
75], nhưng cũng có thể đại diện cho các thùng chứa khác. Tập hợp các phương thức đầu tiên được sử dụng để mô phỏng một chuỗi hoặc mô phỏng ánh xạ; Sự khác biệt là đối với một chuỗi, các khóa cho phép phải là số nguyên k mà
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
76 trong đó n là độ dài của chuỗi hoặc các đối tượng
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
77, xác định một phạm vi của các mục. Chúng tôi cũng khuyến nghị rằng các ánh xạ cung cấp các phương pháp
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
78,
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
79,
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
80,
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
81,
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
82,
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
83,
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
84,
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
85,
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
86 và
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
87 Mô -đun
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
89 cung cấp lớp cơ sở trừu tượng
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
90 để giúp tạo các phương pháp đó từ một bộ cơ sở
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
04,
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
92,
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
93 và
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
78. Các chuỗi có thể thay đổi nên cung cấp các phương pháp
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
95,
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
96,
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
97,
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
98,
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
99,
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
84,
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

01,
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

02 và
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

03, như các đối tượng Python Standard
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
44. Cuối cùng, các loại trình tự nên thực hiện bổ sung [có nghĩa là nối] và nhân [nghĩa là lặp lại] bằng cách xác định các phương thức
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

05,
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

06,
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

07,
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

08,
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

09 và
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

10 được mô tả dưới đây; Họ không nên định nghĩa các toán tử số khác. Chúng tôi khuyến nghị rằng cả hai ánh xạ và trình tự đều thực hiện phương pháp
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

11 để cho phép sử dụng hiệu quả toán tử
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

12; Đối với ánh xạ,
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

12 nên tìm kiếm các phím ánh xạ; Đối với các chuỗi, nó nên tìm kiếm thông qua các giá trị. Chúng tôi khuyến nghị thêm cả ánh xạ và trình tự thực hiện phương pháp
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
19 để cho phép lặp hiệu quả thông qua thùng chứa; Đối với ánh xạ,
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
19 nên lặp lại thông qua các phím đối tượng; Đối với các chuỗi, nó nên lặp lại thông qua các giá trị.sequences [such as
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
73 or
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
74] or mappings [like
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
75], but can represent other containers as well. The first set of methods is used either to emulate a sequence or to emulate a mapping; the difference is that for a sequence, the allowable keys should be the integers k for which
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
76 where N is the length of the sequence, or
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
77 objects, which define a range of items. It is also recommended that mappings provide the methods
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
78,
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
79,
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
80,
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
81,
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
82,
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
83,
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
84,
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
85,
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
86, and
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
87 behaving similar to those for Python’s standard
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
76 objects. The
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
89 module provides a
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
90 abstract base class to help create those methods from a base set of
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
04,
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
92,
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
93, and
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
78. Mutable sequences should provide methods
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
95,
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
96,
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
97,
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
98,
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
99,
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
84,
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

01,
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

02 and
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

03, like Python standard
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
44 objects. Finally, sequence types should implement addition [meaning concatenation] and multiplication [meaning repetition] by defining the methods
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

05,
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

06,
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

07,
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

08,
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

09 and
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

10 described below; they should not define other numerical operators. It is recommended that both mappings and sequences implement the
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

11 method to allow efficient use of the
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

12 operator; for mappings,
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

12 should search the mapping’s keys; for sequences, it should search through the values. It is further recommended that both mappings and sequences implement the
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
19 method to allow efficient iteration through the container; for mappings,
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
19 should iterate through the object’s keys; for sequences, it should iterate through the values.

Đối tượng .__ Len __ [tự] ¶__len__[self]

Được gọi để thực hiện chức năng tích hợp

from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
0. Nên trả về độ dài của đối tượng, số nguyên
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
7 0. Ngoài ra, một đối tượng không xác định phương thức
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
65 và phương thức
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
63 trả về 0 được coi là sai trong bối cảnh boolean.

Chi tiết triển khai CPython: Trong CPython, độ dài được yêu cầu nhất là

>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

20. Nếu độ dài lớn hơn
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

20, một số tính năng [chẳng hạn như
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
0] có thể tăng
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

23. Để ngăn chặn việc tăng
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

23 bằng cách kiểm tra giá trị sự thật, một đối tượng phải xác định phương pháp
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
65.
In CPython, the length is required to be at most
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

20. If the length is larger than
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

20 some features [such as
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
0] may raise
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

23. To prevent raising
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

23 by truth value testing, an object must define a
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
65 method.

đối tượng .__ length_hint __ [tự] ¶__length_hint__[self]

Được gọi để thực hiện

>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

26. Nên trả về một độ dài ước tính cho đối tượng [có thể lớn hơn hoặc nhỏ hơn chiều dài thực tế]. Độ dài phải là một số nguyên
from inspect import isclass

def subscribe[obj, x]:
    """Return the result of the expression 'obj[x]'"""

    class_of_obj = type[obj]

    # If the class of obj defines __getitem__,
    # call class_of_obj.__getitem__[obj, x]
    if hasattr[class_of_obj, '__getitem__']:
        return class_of_obj.__getitem__[obj, x]

    # Else, if obj is a class and defines __class_getitem__,
    # call obj.__class_getitem__[x]
    elif isclass[obj] and hasattr[obj, '__class_getitem__']:
        return obj.__class_getitem__[x]

    # Else, raise an exception
    else:
        raise TypeError[
            f"'{class_of_obj.__name__}' object is not subscriptable"
        ]
7 0. Giá trị trả về cũng có thể là
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
7, được xử lý giống như phương thức
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

29 đã không tồn tại. Phương pháp này hoàn toàn là một tối ưu hóa và không bao giờ được yêu cầu cho sự chính xác.

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

Ghi chú

Cắt được thực hiện độc quyền với ba phương pháp sau. Một cuộc gọi như thế

được dịch sang

và kể từ đó trở đi. Thiếu các mặt hàng lát luôn được điền vào với

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
6.

đối tượng .__ getItem __ [tự, khóa] ¶__getitem__[self, key]

Được gọi để thực hiện đánh giá

>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

31. Đối với các loại trình tự, các khóa được chấp nhận phải là số nguyên và đối tượng lát. Lưu ý rằng cách giải thích đặc biệt của các chỉ số âm [nếu lớp muốn mô phỏng loại trình tự] tùy thuộc vào phương pháp
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
04. Nếu khóa thuộc loại không phù hợp,
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
0 có thể được nâng lên; Nếu có giá trị bên ngoài tập hợp các chỉ mục cho chuỗi [sau khi có bất kỳ cách giải thích đặc biệt nào về các giá trị âm],
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

34 nên được nâng lên. Đối với các loại ánh xạ, nếu thiếu khóa [không phải trong container],
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

35 nên được nâng lên.sequence types, the accepted keys should be integers and slice objects. Note that the special interpretation of negative indexes [if the class wishes to emulate a sequence type] is up to the
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
04 method. If key is of an inappropriate type,
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
0 may be raised; if of a value outside the set of indexes for the sequence [after any special interpretation of negative values],
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

34 should be raised. For mapping types, if key is missing [not in the container],
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

35 should be raised.

Ghi chú

Cắt được thực hiện độc quyền với ba phương pháp sau. Một cuộc gọi như thế

được dịch sang__setitem__[self, key, value]

và kể từ đó trở đi. Thiếu các mặt hàng lát luôn được điền vào với

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
6.

đối tượng .__ getItem __ [tự, khóa] ¶__delitem__[self, key]

Được gọi để thực hiện đánh giá

>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

31. Đối với các loại trình tự, các khóa được chấp nhận phải là số nguyên và đối tượng lát. Lưu ý rằng cách giải thích đặc biệt của các chỉ số âm [nếu lớp muốn mô phỏng loại trình tự] tùy thuộc vào phương pháp
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
04. Nếu khóa thuộc loại không phù hợp,
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
0 có thể được nâng lên; Nếu có giá trị bên ngoài tập hợp các chỉ mục cho chuỗi [sau khi có bất kỳ cách giải thích đặc biệt nào về các giá trị âm],
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

34 nên được nâng lên. Đối với các loại ánh xạ, nếu thiếu khóa [không phải trong container],
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

35 nên được nâng lên.

>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

36 Loops hy vọng rằng một
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

34 sẽ được nêu ra cho các chỉ số bất hợp pháp để cho phép phát hiện đúng về phần cuối của chuỗi.
__missing__[self, key]

đối tượng .__ setItem __ [self, key, giá trị] ¶

Được gọi để thực hiện chuyển nhượng cho
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

31. Tương tự như vậy đối với
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
04. Điều này chỉ nên được thực hiện cho các ánh xạ nếu các đối tượng hỗ trợ thay đổi các giá trị cho các khóa hoặc nếu các khóa mới có thể được thêm vào hoặc cho các chuỗi nếu các phần tử có thể được thay thế. Các trường hợp ngoại lệ tương tự nên được nêu ra cho các giá trị khóa không đúng như đối với phương thức
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
04.
__iter__[self]

Đối tượng .__ Delitem __ [tự, khóa] ¶iterator is required for a container. This method should return a new iterator object that can iterate over all the objects in the container. For mappings, it should iterate over the keys of the container.

Được gọi để thực hiện xóa
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

31. Tương tự như vậy đối với
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
04. Điều này chỉ nên được thực hiện để ánh xạ nếu các đối tượng hỗ trợ loại bỏ các khóa hoặc cho các chuỗi nếu các phần tử có thể được xóa khỏi chuỗi. Các trường hợp ngoại lệ tương tự nên được nêu ra cho các giá trị khóa không đúng như đối với phương thức
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
04.
__reversed__[self]

Đối tượng .__ Thiếu __ [Tự, Key] ¶

Được gọi bởi ________ 423 .________ 304 để thực hiện

>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

31 cho các lớp con dict khi khóa không có trong từ điển.

đối tượng .__ iter __ [tự] ¶

Phương pháp này được gọi là khi một trình lặp được yêu cầu cho một thùng chứa. Phương pháp này sẽ trả về một đối tượng lặp mới có thể lặp lại trên tất cả các đối tượng trong container. Đối với ánh xạ, nó nên lặp lại các khóa của container.__contains__[self, item]

đối tượng .__ đảo ngược __ [bản thân] ¶

Được gọi [nếu có] bởi

>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

47 tích hợp để thực hiện lặp lại. Nó sẽ trả về một đối tượng lặp mới lặp lại trên tất cả các đối tượng trong thùng chứa theo thứ tự ngược lại.this section in the language reference.

Nếu phương thức
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

48 không được cung cấp,
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

47 tích hợp sẽ quay trở lại bằng cách sử dụng giao thức trình tự [
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
63 và
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
04]. Các đối tượng hỗ trợ giao thức trình tự chỉ nên cung cấp
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

48 nếu chúng có thể cung cấp một triển khai hiệu quả hơn so với quy trình được cung cấp bởi
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

47.
Emulating numeric types¶

Các toán tử kiểm tra thành viên [

>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

12 và
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

55] thường được thực hiện dưới dạng lặp qua một container. Tuy nhiên, các đối tượng container có thể cung cấp phương pháp đặc biệt sau đây với việc triển khai hiệu quả hơn, điều này cũng không yêu cầu đối tượng phải có thể sử dụng được.

Đối tượng .__ Thêm __ [bản thân, khác] ¶ Đối tượng .__ sub __ [tự, khác] ¶ đối tượng .__ mul __ [tự, khác] đối tượng .__ matmul __ [tự, khác] Đối tượng .__ Truediv __ , Khác] Đối tượng .__ Mod __ [Tự, Khác] ¶ Đối tượng .__ Divmod __ [Tự, Khác] Đối tượng. Khác] Đối tượng .__ và __ [tự, khác] Đối tượng .__ XOR__add__[self, other]object.__sub__[self, other]object.__mul__[self, other]object.__matmul__[self, other]object.__truediv__[self, other]object.__floordiv__[self, other]object.__mod__[self, other]object.__divmod__[self, other]object.__pow__[self, other[, modulo]]object.__lshift__[self, other]object.__rshift__[self, other]object.__and__[self, other]object.__xor__[self, other]object.__or__[self, other]

Các phương pháp này được gọi để thực hiện các hoạt động số học nhị phân [

>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

59,
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

60,
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

61,
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

62,
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

63,
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

64,
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

65,
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

66, ____767, ____7 Chẳng hạn, để đánh giá biểu thức
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

74, trong đó x là một thể hiện của một lớp có phương pháp
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

05,
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

76 được gọi. Phương pháp
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

77 phải tương đương với việc sử dụng
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

78 và
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

79; Nó không nên liên quan đến
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

80. Lưu ý rằng
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

81 nên được xác định để chấp nhận đối số thứ ba tùy chọn nếu phiên bản ternary của hàm
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

67 tích hợp được hỗ trợ.

Nếu một trong những phương pháp đó không hỗ trợ hoạt động với các đối số được cung cấp, nó sẽ trả về

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
7.

đối tượng .__ radd __ [tự, khác] ¶ đối tượng .__ rsub __ [tự, khác] ¶ đối tượng .__ rmul __ [tự, khác] ¶ đối tượng .__ rmatmul __ [tự, khác] ¶ Đối tượng. , khác] Đối tượng .__ rmod __ [tự, khác] ¶ Đối tượng .__ rdivmod __ [tự, khác] ¶ đối tượng .__ rpow __ [tự, khác [, modulo]] ¶ đối tượng .__ rlshift __ [tự, khác] đối tượng .__ rrshift Khác] Đối tượng .__ Rand __ [tự, khác] Đối tượng.__radd__[self, other]object.__rsub__[self, other]object.__rmul__[self, other]object.__rmatmul__[self, other]object.__rtruediv__[self, other]object.__rfloordiv__[self, other]object.__rmod__[self, other]object.__rdivmod__[self, other]object.__rpow__[self, other[, modulo]]object.__rlshift__[self, other]object.__rrshift__[self, other]object.__rand__[self, other]object.__rxor__[self, other]object.__ror__[self, other]

Các phương pháp này được gọi để thực hiện các hoạt động số học nhị phân [

>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

59,
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

60,
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

61,
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

62,
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

63,
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

64,
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

65,
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

66, ____3, ____3. Các chức năng này chỉ được gọi nếu toán hạng bên trái không hỗ trợ hoạt động 3 tương ứng và các toán hạng có các loại khác nhau. 4 Ví dụ, để đánh giá biểu thức
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

99, trong đó y là một thể hiện của một lớp có phương pháp
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

00,
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

01 được gọi nếu
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

02 trả về không kích thích.

Lưu ý rằng ternary

>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

67 sẽ không thử gọi
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

04 [các quy tắc cưỡng chế sẽ trở nên quá phức tạp].

Ghi chú

Nếu loại toán hạng bên phải là một lớp con thuộc loại toán hạng bên trái và lớp con đó cung cấp một triển khai khác của phương thức phản xạ cho hoạt động, phương thức này sẽ được gọi trước phương thức không được phản ánh của toán hạng bên trái. Hành vi này cho phép các lớp con ghi đè lên các hoạt động của tổ tiên của họ.

Đối tượng .__ IADD __ [bản thân, khác] Đối tượng .__ isub __ [tự, khác] ¶ Đối tượng .__ IMUL __ [tự, khác] ¶ đối tượng .__ Imatmul __ , Khác] Đối tượng .__ Imod __ [tự, khác] ¶ Đối tượng. Khác] Đối tượng .__ Ixor __ [tự, khác] Đối tượng__iadd__[self, other]object.__isub__[self, other]object.__imul__[self, other]object.__imatmul__[self, other]object.__itruediv__[self, other]object.__ifloordiv__[self, other]object.__imod__[self, other]object.__ipow__[self, other[, modulo]]object.__ilshift__[self, other]object.__irshift__[self, other]object.__iand__[self, other]object.__ixor__[self, other]object.__ior__[self, other]

Các phương pháp này được gọi để thực hiện các nhiệm vụ số học tăng cường [

>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

05,
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

06,
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

07,
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

08,
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

09,
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

10,
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

11,
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

12,
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

13, ____. Các phương pháp này nên cố gắng thực hiện thao tác tại chỗ [tự sửa đổi bản thân] và trả về kết quả [có thể, nhưng không cần phải tự, bản thân]. Nếu một phương pháp cụ thể không được xác định, nhiệm vụ tăng cường rơi trở lại các phương pháp bình thường. Chẳng hạn, nếu X là một thể hiện của một lớp có phương thức
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

07,
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

19 tương đương với
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

20. Mặt khác,
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

21 và
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

22 được xem xét, như với việc đánh giá
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

74. Trong một số tình huống nhất định, việc gán tăng cường có thể dẫn đến các lỗi không mong muốn [xem tại sao a_tuple [i] += [‘item,] nêu ra một ngoại lệ khi bổ sung hoạt động?], Nhưng hành vi này thực sự là một phần của mô hình dữ liệu.Why does a_tuple[i] += [‘item’] raise an exception when the addition works?], but this behavior is in fact part of the data model.

Đối tượng .__ Neg__neg__[self]object.__pos__[self]object.__abs__[self]object.__invert__[self]

Được gọi để thực hiện các hoạt động số học không [

>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

60,
>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

59,
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

26 và
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

27].

đối tượng .__ phức tạp __ [tự] ¶ đối tượng .__ int __ [self] ¶ đối tượng .__ float __ [self] ¶__complex__[self]object.__int__[self]object.__float__[self]

Được gọi để thực hiện các chức năng tích hợp

>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

28,
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

29 và
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

30. Nên trả về một giá trị của loại thích hợp.

Đối tượng .__ INDEX __ [tự] ¶__index__[self]

Được gọi để thực hiện

>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

31 và bất cứ khi nào Python cần chuyển đổi đối tượng số thành một đối tượng số nguyên [chẳng hạn như trong cắt, hoặc trong các hàm
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

32,
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

33 và
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

34 tích hợp]. Sự hiện diện của phương pháp này chỉ ra rằng đối tượng số là một loại số nguyên. Phải trả về một số nguyên.

Nếu

>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

35,
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

36 và
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

37 không được xác định thì các hàm tích hợp tương ứng
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

29,
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

30 và
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

28 rơi trở lại
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

41.

Đối tượng .__ Vòng __ [tự [, ndigits]] ¶ Đối tượng.__round__[self[, ndigits]]object.__trunc__[self]object.__floor__[self]object.__ceil__[self]

Được gọi để thực hiện chức năng tích hợp

>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

42 và
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
70
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

44,
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

45 và
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

46. Trừ khi NDigits được chuyển đến
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

47, tất cả các phương thức này sẽ trả về giá trị của đối tượng bị cắt ngắn thành
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

48 [thường là
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
7].

Hàm tích hợp

>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

29 rơi trở lại
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

51 nếu không xác định
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

35 và
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

41.

Đã thay đổi trong phiên bản 3.11: Phái đoàn của

>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

29 thành
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

51 không được chấp nhận.The delegation of
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

29 to
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

51 is deprecated.

3.3.9. Với các nhà quản lý bối cảnh tuyên bốWith Statement Context Managers¶

Trình quản lý bối cảnh là một đối tượng xác định bối cảnh thời gian chạy sẽ được thiết lập khi thực hiện câu lệnh

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
6. Trình quản lý bối cảnh xử lý mục nhập vào và thoát khỏi bối cảnh thời gian chạy mong muốn để thực hiện khối mã. Các nhà quản lý bối cảnh thường được gọi bằng cách sử dụng câu lệnh
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
6 [được mô tả trong phần với câu lệnh với câu lệnh], nhưng cũng có thể được sử dụng bằng cách gọi trực tiếp các phương thức của họ.The with statement], but can also be used by directly invoking their methods.

Việc sử dụng điển hình của các nhà quản lý bối cảnh bao gồm lưu và khôi phục các loại trạng thái toàn cầu, khóa và mở khóa tài nguyên, đóng các tệp đã mở, v.v.

Để biết thêm thông tin về người quản lý ngữ cảnh, hãy xem các loại Trình quản lý ngữ cảnh.Context Manager Types.

Đối tượng .__ Nhập __ [tự] ¶__enter__[self]

Nhập bối cảnh thời gian chạy liên quan đến đối tượng này. Câu lệnh

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
6 sẽ liên kết giá trị trả về phương thức này với [các] mục tiêu được chỉ định trong mệnh đề
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

59 của câu lệnh, nếu có.

Đối tượng .__ Thoát __ [self, exc_type, exc_value, traceback] ¶__exit__[self, exc_type, exc_value, traceback]

Thoát khỏi bối cảnh thời gian chạy liên quan đến đối tượng này. Các tham số mô tả ngoại lệ khiến bối cảnh bị thoát ra. Nếu bối cảnh bị thoát ra mà không có ngoại lệ, cả ba đối số sẽ là

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
6.

Nếu một ngoại lệ được cung cấp và phương pháp muốn triệt tiêu ngoại lệ [nghĩa là, ngăn không cho nó được nhân giống], nó sẽ trả về một giá trị thực. Nếu không, ngoại lệ sẽ được xử lý bình thường khi thoát khỏi phương pháp này.

Lưu ý rằng các phương thức

>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

61 không nên làm lại ngoại lệ được thông qua; Đây là trách nhiệm của người gọi.

Xem thêm

PEP 343 - Tuyên bố với "với" - The “with” statement

Đặc điểm kỹ thuật, nền và ví dụ cho câu lệnh Python

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
6.

3.3.10. Tùy chỉnh các đối số vị trí trong mô hình lớp phù hợpCustomizing positional arguments in class pattern matching¶

Khi sử dụng tên lớp trong một mẫu, các đối số vị trí trong mẫu không được phép theo mặc định, tức là

>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

63 thường không hợp lệ mà không có hỗ trợ đặc biệt trong
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
96. Để có thể sử dụng loại mẫu đó, lớp cần xác định thuộc tính __match_args__.

Đối tượng .__ Match_args__¶__match_args__

Biến lớp này có thể được gán một bộ chuỗi. Khi lớp này được sử dụng trong một mẫu lớp với các đối số vị trí, mỗi đối số vị trí sẽ được chuyển đổi thành đối số từ khóa, sử dụng giá trị tương ứng trong __match_args__ làm từ khóa. Sự vắng mặt của thuộc tính này tương đương với việc đặt nó thành

>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

65.

Ví dụ: nếu

>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

66 là
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

67 có nghĩa là
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

63 tương đương với
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

69. Lưu ý rằng số lượng đối số trong mẫu phải nhỏ hơn hoặc bằng số lượng phần tử trong __match_args__; Nếu nó lớn hơn, nỗ lực khớp mẫu sẽ tăng
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
0.

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

Xem thêm

PEP 343 - Tuyên bố với "với" - Structural Pattern Matching

Đặc điểm kỹ thuật, nền và ví dụ cho câu lệnh Python

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
6.

3.3.10. Tùy chỉnh các đối số vị trí trong mô hình lớp phù hợpSpecial method lookup¶

Khi sử dụng tên lớp trong một mẫu, các đối số vị trí trong mẫu không được phép theo mặc định, tức là

>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

63 thường không hợp lệ mà không có hỗ trợ đặc biệt trong
class Meta[type]:
    pass

class MyClass[metaclass=Meta]:
    pass

class MySubclass[MyClass]:
    pass
96. Để có thể sử dụng loại mẫu đó, lớp cần xác định thuộc tính __match_args__.

>>> class C:
...     pass
...
>>> c = C[]
>>> c.__len__ = lambda: 5
>>> len[c]
Traceback [most recent call last]:
  File "", line 1, in 
TypeError: object of type 'C' has no len[]

Đối tượng .__ Match_args__¶

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
0

Biến lớp này có thể được gán một bộ chuỗi. Khi lớp này được sử dụng trong một mẫu lớp với các đối số vị trí, mỗi đối số vị trí sẽ được chuyển đổi thành đối số từ khóa, sử dụng giá trị tương ứng trong __match_args__ làm từ khóa. Sự vắng mặt của thuộc tính này tương đương với việc đặt nó thành

>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

65.

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
1

Ví dụ: nếu

>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

66 là
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

67 có nghĩa là
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

63 tương đương với
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

69. Lưu ý rằng số lượng đối số trong mẫu phải nhỏ hơn hoặc bằng số lượng phần tử trong __match_args__; Nếu nó lớn hơn, nỗ lực khớp mẫu sẽ tăng
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
0.

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
2

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

3.4. Coroutines¶Coroutines¶

3.4.1. Đối tượng đang chờ đợiAwaitable Objects¶

Một đối tượng có thể chờ đợi thường thực hiện một phương thức

>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

76. Các đối tượng Coroutine được trả về từ các chức năng
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
57 có thể chờ được.awaitable object generally implements an
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

76 method. Coroutine objects returned from
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
57 functions are awaitable.

đối tượng .__ chờ đợi __ [bản thân] ¶__await__[self]

Phải trả về một trình lặp. Nên được sử dụng để thực hiện các đối tượng đang chờ đợi. Chẳng hạn,

>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

78 thực hiện phương pháp này để tương thích với biểu thức
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
58.iterator. Should be used to implement awaitable objects. For instance,
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

78 implements this method to be compatible with the
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
58 expression.

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

Xem thêm

PEP 492 để biết thêm thông tin về các đối tượng đang chờ đợi. for additional information about awaitable objects.

3.4.2. Đối tượng CoroutineCoroutine Objects¶

Các đối tượng Coroutine là các đối tượng có thể chờ đợi. Việc thực hiện Coroutine có thể được kiểm soát bằng cách gọi

>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

76 và lặp lại kết quả. Khi coroutine đã hoàn tất việc thực thi và trả lại, trình lặp lại tăng
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
56 và thuộc tính ngoại lệ ____ ____492 giữ giá trị trả về. Nếu coroutine làm tăng một ngoại lệ, nó được truyền bởi người lặp. Coroutines không nên trực tiếp nâng cao các ngoại lệ
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
56. are awaitable objects. A coroutine’s execution can be controlled by calling
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

76 and iterating over the result. When the coroutine has finished executing and returns, the iterator raises
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
56, and the exception’s
class A:
   pass

c = C[]
A.x = c                  # The hook is not called
c.__set_name__[A, 'x']   # Manually invoke the hook
92 attribute holds the return value. If the coroutine raises an exception, it is propagated by the iterator. Coroutines should not directly raise unhandled
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
56 exceptions.

Coroutines cũng có các phương thức được liệt kê dưới đây, tương tự như các phương thức của các trình tạo [xem phương thức máy phát điện]. Tuy nhiên, không giống như máy phát điện, coroutines không hỗ trợ trực tiếp lặp lại.Generator-iterator methods]. However, unlike generators, coroutines do not directly support iteration.

Đã thay đổi trong phiên bản 3.5.2: Đó là một

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
87 để chờ đợi một coroutine nhiều lần.It is a
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
87 to await on a coroutine more than once.

coroutine.send [giá trị] ¶send[value]

Bắt đầu hoặc tiếp tục thực hiện coroutine. Nếu giá trị là

class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
6, thì điều này tương đương với việc thúc đẩy trình lặp được trả về bởi
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

76. Nếu giá trị không phải là
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
6, phương pháp này ủy quyền cho phương thức
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

88 của trình lặp lại khiến coroutine bị đình chỉ. Kết quả [giá trị trả về,
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
56 hoặc ngoại lệ khác] giống như khi lặp lại giá trị trả về
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

76, được mô tả ở trên.

Coroutine.throw [Giá trị] ¶ Coroutine.throw [Loại [, Giá trị [, Traceback]]]]throw[value]coroutine.throw[type[, value[, traceback]]]

Tăng ngoại lệ được chỉ định trong Coroutine. Phương pháp này giao cho phương pháp

>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

91 của trình lặp khiến coroutine bị đình chỉ, nếu nó có một phương pháp như vậy. Nếu không, ngoại lệ được nâng lên tại điểm đình chỉ. Kết quả [giá trị trả về,
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
56 hoặc ngoại lệ khác] giống như khi lặp lại giá trị trả về
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

76, được mô tả ở trên. Nếu ngoại lệ không bị bắt trong coroutine, nó sẽ truyền lại cho người gọi.

coroutine.close []close[]

Làm cho coroutine tự dọn dẹp và thoát ra. Nếu coroutine bị đình chỉ, phương pháp này lần đầu tiên ủy thác cho phương pháp

class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
3 của trình lặp khiến coroutine bị đình chỉ, nếu nó có một phương pháp như vậy. Sau đó, nó tăng
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

95 tại điểm treo, khiến Coroutine tự dọn dẹp ngay lập tức. Cuối cùng, coroutine được đánh dấu là đã thực hiện xong, ngay cả khi nó không bao giờ được bắt đầu.

Các đối tượng Coroutine được tự động đóng bằng cách sử dụng quy trình trên khi chúng sắp bị phá hủy.

3.4.3. Tererators không đồng bộAsynchronous Iterators¶

Một trình lặp không đồng bộ có thể gọi mã không đồng bộ theo phương thức

>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

96 của nó.

Các trình lặp không đồng bộ có thể được sử dụng trong một câu lệnh

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
60.

Đối tượng .__ Aiter __ [tự] ¶__aiter__[self]

Phải trả về một đối tượng lặp không đồng bộ.

đối tượng .__ anext __ [tự] ¶__anext__[self]

Phải trả về một sự chờ đợi có thể chờ đợi trong một giá trị tiếp theo của trình lặp. Nên tăng lỗi

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
67 khi lần lặp kết thúc.

Một ví dụ về một đối tượng có thể lặp không đồng bộ:

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
3

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

Xem thêmPrior to Python 3.7,

>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

99 could return an awaitable that would resolve to an asynchronous iterator.

PEP 492 để biết thêm thông tin về các đối tượng đang chờ đợi.

3.4.2. Đối tượng CoroutineAsynchronous Context Managers¶

Các đối tượng Coroutine là các đối tượng có thể chờ đợi. Việc thực hiện Coroutine có thể được kiểm soát bằng cách gọi

>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

76 và lặp lại kết quả. Khi coroutine đã hoàn tất việc thực thi và trả lại, trình lặp lại tăng
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
56 và thuộc tính ngoại lệ ____ ____492 giữ giá trị trả về. Nếu coroutine làm tăng một ngoại lệ, nó được truyền bởi người lặp. Coroutines không nên trực tiếp nâng cao các ngoại lệ
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
56.

Coroutines cũng có các phương thức được liệt kê dưới đây, tương tự như các phương thức của các trình tạo [xem phương thức máy phát điện]. Tuy nhiên, không giống như máy phát điện, coroutines không hỗ trợ trực tiếp lặp lại.

Đã thay đổi trong phiên bản 3.5.2: Đó là một
class Philosopher:
    def __init_subclass__[cls, /, default_name, **kwargs]:
        super[].__init_subclass__[**kwargs]
        cls.default_name = default_name

class AustralianPhilosopher[Philosopher, default_name="Bruce"]:
    pass
87 để chờ đợi một coroutine nhiều lần.
__aenter__[self]

coroutine.send [giá trị] ¶

Bắt đầu hoặc tiếp tục thực hiện coroutine. Nếu giá trị là
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
6, thì điều này tương đương với việc thúc đẩy trình lặp được trả về bởi
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

76. Nếu giá trị không phải là
class A:
    x = C[]  # Automatically calls: x.__set_name__[A, 'x']
6, phương pháp này ủy quyền cho phương thức
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

88 của trình lặp lại khiến coroutine bị đình chỉ. Kết quả [giá trị trả về,
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
56 hoặc ngoại lệ khác] giống như khi lặp lại giá trị trả về
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

76, được mô tả ở trên.
__aexit__[self, exc_type, exc_value, traceback]

Coroutine.throw [Giá trị] ¶ Coroutine.throw [Loại [, Giá trị [, Traceback]]]]

Tăng ngoại lệ được chỉ định trong Coroutine. Phương pháp này giao cho phương pháp

>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

91 của trình lặp khiến coroutine bị đình chỉ, nếu nó có một phương pháp như vậy. Nếu không, ngoại lệ được nâng lên tại điểm đình chỉ. Kết quả [giá trị trả về,
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
56 hoặc ngoại lệ khác] giống như khi lặp lại giá trị trả về
>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

76, được mô tả ở trên. Nếu ngoại lệ không bị bắt trong coroutine, nó sẽ truyền lại cho người gọi.

import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
4

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

Xem thêm

1

PEP 492 để biết thêm thông tin về các đối tượng đang chờ đợi.

2

3.4.2. Đối tượng Coroutine

3

Các đối tượng Coroutine là các đối tượng có thể chờ đợi. Việc thực hiện Coroutine có thể được kiểm soát bằng cách gọi

>>> from enum import Enum
>>> class Menu[Enum]:
...     """A breakfast menu"""
...     SPAM = 'spam'
...     BACON = 'bacon'
...
>>> # Enum classes have a custom metaclass:
>>> type[Menu]

>>> # EnumMeta defines __getitem__,
>>> # so __class_getitem__ is not called,
>>> # and the result is not a GenericAlias object:
>>> Menu['SPAM']

>>> type[Menu['SPAM']]

76 và lặp lại kết quả. Khi coroutine đã hoàn tất việc thực thi và trả lại, trình lặp lại tăng
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
56 và thuộc tính ngoại lệ ____ ____492 giữ giá trị trả về. Nếu coroutine làm tăng một ngoại lệ, nó được truyền bởi người lặp. Coroutines không nên trực tiếp nâng cao các ngoại lệ
import sys
from types import ModuleType

class VerboseModule[ModuleType]:
    def __repr__[self]:
        return f'Verbose {self.__name__}'

    def __setattr__[self, attr, value]:
        print[f'Setting {attr}...']
        super[].__setattr__[attr, value]

sys.modules[__name__].__class__ = VerboseModule
56.

4

Đối với các toán hạng cùng loại, giả định rằng nếu phương pháp không được phản ánh-chẳng hạn như

>>> # list has class "type" as its metaclass, like most classes:
>>> type[list]

>>> type[dict] == type[list] == type[tuple] == type[str] == type[bytes]
True
>>> # "list[int]" calls "list.__class_getitem__[int]"
>>> list[int]
list[int]
>>> # list.__class_getitem__ returns a GenericAlias object:
>>> type[list[int]]

05-không thành công thì hoạt động tổng thể không được hỗ trợ, đó là lý do tại sao phương pháp được phản ánh không được gọi.

Làm thế nào để bạn tạo một lớp mô hình trong Python?

Các lớp và đối tượng Python..
Tạo một lớp học. Để tạo một lớp, hãy sử dụng lớp từ khóa: ....
Tạo đối tượng. Bây giờ chúng ta có thể sử dụng lớp có tên MyClass để tạo các đối tượng: ....
Tham số tự. ....
Sửa đổi thuộc tính đối tượng. ....
Xóa thuộc tính đối tượng. ....
Xóa đối tượng ..

Làm thế nào để bạn tạo một mô hình dữ liệu trong Python?

Các phương pháp đặc biệt để mô hình hóa dữ liệu trong Python..
Phương thức __init __ [] là để khởi tạo và được gọi bởi chính trình thông dịch Python khi một thể hiện của một đối tượng được tạo ..
Phương pháp Len [x] dành cho tính toán độ dài của một đối tượng, bên trong trình thông dịch Python gọi X .__ Len [].

__ Lớp __ trong Python là gì?

__ class__ là một thuộc tính trên đối tượng đề cập đến lớp mà từ đó đối tượng được tạo.một.__Class__ # Đầu ra: b.__Class__ # Đầu ra: Sau các loại dữ liệu đơn giản, giờ đây chúng ta hãy hiểu chức năng loại và __Class__ với sự trợ giúp của lớp do người dùng xác định, con người.an attribute on the object that refers to the class from which the object was created. a. __class__ # Output: b. __class__ # Output: After simple data types, let's now understand the type function and __class__ attribute with the help of a user-defined class, Human .

__ chứa __ trong Python là gì?

Chuỗi Python __Contains __ [] là một phương thức thể hiện và trả về giá trị boolean true hay false tùy thuộc vào việc đối tượng chuỗi có chứa đối tượng chuỗi được chỉ định hay không.Lưu ý rằng chuỗi Python chứa phương thức [] là trường hợp nhạy cảm.an instance method and returns boolean value True or False depending on whether the string object contains the specified string object or not. Note that the Python string contains[] method is case sensitive.

Bài Viết Liên Quan

Chủ Đề