Hướng dẫn c++ type of current class - C++ loại lớp hiện tại

Bạn có thể sử dụng thủ thuật sau:

Show
#define SELF \
    static auto helper() -> std::remove_reference::type; \
    typedef decltype(helper()) self

struct A {
    SELF;
};

Tôi tuyên bố một hàm trợ giúp bằng cách sử dụng loại trả về

 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
3, cho phép tôi sử dụng
 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
4 làm loại trả lại, không biết tên lớp là gì. Sau đó, tôi có thể sử dụng
 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
5 để sử dụng loại lớp trong mã. Lưu ý rằng hàm phải là
 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
6, nếu không bạn không thể sử dụng nó trong
 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
7. Ngoài ra, chức năng chỉ được khai báo, không được xác định; Đây không phải là một vấn đề vì dù sao bạn cũng sẽ không gọi nó. .

Sau đó, bạn có thể sử dụng

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
1 typedef để khai báo thêm hoặc chỉ thay đổi macro thành typedef chứ không phải bản thân lớp, mà là những gì bạn cần. Điều chỉnh nó cho phù hợp với nhu cầu cụ thể của bạn.

Cập nhật: Đây dường như là một hành vi không chuẩn của GCC. Ví dụ: ICC không cho phép

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
2 trong các chức năng
 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
6 ngay cả trong loại trả về theo dõi.
: This seems to be a non-standard behavior of GCC. For example, ICC does not allow
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
2 in
 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
6 functions even in trailing return type.

Xem bây giờ hướng dẫn này có một khóa học video liên quan được tạo bởi nhóm Python thực sự. Xem nó cùng với hướng dẫn bằng văn bản để hiểu sâu hơn về sự hiểu biết của bạn: Sử dụng các trình xây dựng lớp Python This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Using Python Class Constructors

Các hàm tạo lớp là một phần cơ bản của lập trình hướng đối tượng trong Python. Chúng cho phép bạn tạo và khởi tạo đúng các đối tượng của một lớp nhất định, làm cho các đối tượng đó sẵn sàng sử dụng. Các trình xây dựng lớp kích hoạt nội bộ quá trình khởi tạo Python, chạy qua hai bước chính: Tạo và khởi tạo thể hiện.object-oriented programming in Python. They allow you to create and properly initialize objects of a given class, making those objects ready to use. Class constructors internally trigger Python’s instantiation process, which runs through two main steps: instance creation and instance initialization.

Nếu bạn muốn đi sâu hơn về cách Python xây dựng các đối tượng và tìm hiểu cách tùy chỉnh quy trình, thì hướng dẫn này dành cho bạn.

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

  • Hiểu quá trình khởi tạo nội bộ của Pythoninstantiation process
  • Tùy chỉnh khởi tạo đối tượng bằng cách sử dụng
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    4
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    4
  • Tinh chỉnh việc tạo đối tượng bằng cách ghi đè
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    5
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    5

Với kiến ​​thức này, bạn sẽ có thể điều chỉnh việc tạo và khởi tạo các đối tượng trong các lớp Python tùy chỉnh của bạn, điều này sẽ cho phép bạn kiểm soát quá trình khởi tạo ở cấp độ nâng cao hơn.

Để hiểu rõ hơn các ví dụ và khái niệm trong hướng dẫn này, bạn nên quen thuộc với lập trình hướng đối tượng và các phương pháp đặc biệt trong Python.

Các nhà xây dựng lớp Python và quá trình khởi tạo

Giống như nhiều ngôn ngữ lập trình khác, Python hỗ trợ lập trình hướng đối tượng. Tại trung tâm của các khả năng hướng đối tượng của Python, bạn sẽ tìm thấy từ khóa

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
6, cho phép bạn xác định các lớp tùy chỉnh có thể có thuộc tính để lưu trữ dữ liệu và phương thức để cung cấp hành vi.

Khi bạn có một lớp để làm việc, thì bạn có thể bắt đầu tạo các phiên bản hoặc đối tượng mới của lớp đó, đây là một cách hiệu quả để sử dụng lại chức năng trong mã của bạn.instances or objects of that class, which is an efficient way to reuse functionality in your code.

Tạo và khởi tạo các đối tượng của một lớp nhất định là một bước cơ bản trong lập trình hướng đối tượng. Bước này thường được gọi là xây dựng đối tượng hoặc khởi tạo. Công cụ chịu trách nhiệm chạy quá trình khởi tạo này thường được gọi là hàm tạo lớp.object construction or instantiation. The tool responsible for running this instantiation process is commonly known as a class constructor.

Làm quen với các nhà xây dựng lớp Python

Trong Python, để xây dựng một đối tượng của một lớp nhất định, bạn chỉ cần gọi lớp với các đối số thích hợp, như bạn sẽ gọi bất kỳ chức năng nào:

>>>

>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>

Trong ví dụ này, bạn xác định

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
7 bằng cách sử dụng từ khóa
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
6. Lớp này hiện đang trống vì nó không có thuộc tính hoặc phương thức. Thay vào đó, cơ thể lớp lớp chỉ chứa một tuyên bố
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
9 như một tuyên bố giữ chỗ không làm gì cả.

Sau đó, bạn tạo một thể hiện mới của

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
7 bằng cách gọi lớp với một cặp dấu ngoặc đơn. Trong ví dụ này, bạn không cần phải vượt qua bất kỳ đối số nào trong cuộc gọi vì lớp của bạn không có lập luận.

Trong Python, khi bạn gọi một lớp như bạn đã làm trong ví dụ trên, bạn sẽ gọi hàm tạo lớp, tạo ra, khởi tạo và trả về một đối tượng mới bằng cách kích hoạt quá trình khởi tạo nội bộ của Python.

Một điểm cuối cùng cần lưu ý là việc gọi một lớp không giống như gọi là một thể hiện của một lớp. Đây là hai chủ đề khác nhau và không liên quan. Để thực hiện một phiên bản lớp có thể gọi được, bạn cần thực hiện một phương thức đặc biệt

>>> from point import Point

>>> point = Point.__new__(Point)
1. Create a new instance of Point.

>>> # The point object is not initialized
>>> point.x
Traceback (most recent call last):
    ...
AttributeError: 'Point' object has no attribute 'x'
>>> point.y
Traceback (most recent call last):
    ...
AttributeError: 'Point' object has no attribute 'y'

>>> point.__init__(21, 42)
2. Initialize the new instance of Point.

>>> # Now point is properly initialized
>>> point
Point(x=21, y=42)
1, không liên quan gì đến quá trình khởi tạo Python.

Hiểu quá trình khởi tạo Python

Bạn kích hoạt quá trình khởi tạo Python, bất cứ khi nào bạn gọi một lớp Python để tạo một thể hiện mới. Quá trình này chạy qua hai bước riêng biệt, mà bạn có thể mô tả như sau:instantiation process whenever you call a Python class to create a new instance. This process runs through two separate steps, which you can describe as follows:

  1. Tạo một thể hiện mới của lớp đích of the target class
  2. Khởi tạo thể hiện mới với trạng thái ban đầu thích hợp with an appropriate initial state

Để chạy bước đầu tiên, các lớp Python có một phương pháp đặc biệt gọi là

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
5, chịu trách nhiệm tạo và trả về một đối tượng trống mới. Sau đó, một phương pháp đặc biệt khác,
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4, lấy đối tượng kết quả, cùng với các đối số của hàm tạo lớp.

Phương thức

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4 lấy đối tượng mới làm đối số đầu tiên của nó,
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
1. Sau đó, nó đặt bất kỳ thuộc tính thể hiện bắt buộc nào thành trạng thái hợp lệ bằng cách sử dụng các đối số mà hàm tạo lớp được truyền cho nó.

Nói tóm lại, quá trình khởi tạo Python, bắt đầu bằng một cuộc gọi đến Trình xây dựng lớp, điều này kích hoạt người tạo phiên bản,

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
5, để tạo một đối tượng trống mới. Quá trình tiếp tục với trình khởi tạo thể hiện,
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4, lấy các đối số của hàm tạo để khởi tạo đối tượng mới được tạo.instance creator,
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
5, to create a new empty object. The process continues with the instance initializer,
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4, which takes the constructor’s arguments to initialize the newly created object.

Để khám phá cách thức quá trình khởi tạo Python, hoạt động nội bộ, hãy xem xét ví dụ sau đây của lớp

>>> from point import Point

>>> point = Point.__new__(Point)
1. Create a new instance of Point.

>>> # The point object is not initialized
>>> point.x
Traceback (most recent call last):
    ...
AttributeError: 'Point' object has no attribute 'x'
>>> point.y
Traceback (most recent call last):
    ...
AttributeError: 'Point' object has no attribute 'y'

>>> point.__init__(21, 42)
2. Initialize the new instance of Point.

>>> # Now point is properly initialized
>>> point
Point(x=21, y=42)
8 thực hiện phiên bản tùy chỉnh của cả hai phương thức,
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
5 và
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4, cho mục đích trình diễn:

 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"

Ở đây, một sự cố về những gì mã này làm:

  • Dòng 3 xác định lớp

    >>> from point import Point
    
    >>> point = Point.__new__(Point)
    1. Create a new instance of Point.
    
    >>> # The point object is not initialized
    >>> point.x
    Traceback (most recent call last):
        ...
    AttributeError: 'Point' object has no attribute 'x'
    >>> point.y
    Traceback (most recent call last):
        ...
    AttributeError: 'Point' object has no attribute 'y'
    
    >>> point.__init__(21, 42)
    2. Initialize the new instance of Point.
    
    >>> # Now point is properly initialized
    >>> point
    Point(x=21, y=42)
    
    8 bằng cách sử dụng từ khóa
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    6 theo sau là tên lớp.
    defines the
    >>> from point import Point
    
    >>> point = Point.__new__(Point)
    1. Create a new instance of Point.
    
    >>> # The point object is not initialized
    >>> point.x
    Traceback (most recent call last):
        ...
    AttributeError: 'Point' object has no attribute 'x'
    >>> point.y
    Traceback (most recent call last):
        ...
    AttributeError: 'Point' object has no attribute 'y'
    
    >>> point.__init__(21, 42)
    2. Initialize the new instance of Point.
    
    >>> # Now point is properly initialized
    >>> point
    Point(x=21, y=42)
    
    8 class using the
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    6 keyword followed by the class name.

  • Dòng 4 xác định phương thức

    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    5, lấy lớp làm đối số đầu tiên. Lưu ý rằng sử dụng
    # ab_classes.py
    
    class A:
        def __init__(self, a_value):
            print("Initialize the new instance of A.")
            self.a_value = a_value
    
    class B:
        def __new__(cls, *args, **kwargs):
            return A(42)
    
        def __init__(self, b_value):
            print("Initialize the new instance of B.")
            self.b_value = b_value
    
    4 làm tên của đối số này là một quy ước mạnh mẽ trong Python, giống như sử dụng
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    1 để đặt tên cho phiên bản hiện tại là. Phương pháp này cũng mất
    # ab_classes.py
    
    class A:
        def __init__(self, a_value):
            print("Initialize the new instance of A.")
            self.a_value = a_value
    
    class B:
        def __new__(cls, *args, **kwargs):
            return A(42)
    
        def __init__(self, b_value):
            print("Initialize the new instance of B.")
            self.b_value = b_value
    
    6 và
    # ab_classes.py
    
    class A:
        def __init__(self, a_value):
            print("Initialize the new instance of A.")
            self.a_value = a_value
    
    class B:
        def __new__(cls, *args, **kwargs):
            return A(42)
    
        def __init__(self, b_value):
            print("Initialize the new instance of B.")
            self.b_value = b_value
    
    7, cho phép chuyển một số lượng đối số khởi tạo không xác định cho trường hợp cơ bản.
    defines the
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    5 method, which takes the class as its first argument. Note that using
    # ab_classes.py
    
    class A:
        def __init__(self, a_value):
            print("Initialize the new instance of A.")
            self.a_value = a_value
    
    class B:
        def __new__(cls, *args, **kwargs):
            return A(42)
    
        def __init__(self, b_value):
            print("Initialize the new instance of B.")
            self.b_value = b_value
    
    4 as the name of this argument is a strong convention in Python, just like using
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    1 to name the current instance is. The method also takes
    # ab_classes.py
    
    class A:
        def __init__(self, a_value):
            print("Initialize the new instance of A.")
            self.a_value = a_value
    
    class B:
        def __new__(cls, *args, **kwargs):
            return A(42)
    
        def __init__(self, b_value):
            print("Initialize the new instance of B.")
            self.b_value = b_value
    
    6 and
    # ab_classes.py
    
    class A:
        def __init__(self, a_value):
            print("Initialize the new instance of A.")
            self.a_value = a_value
    
    class B:
        def __new__(cls, *args, **kwargs):
            return A(42)
    
        def __init__(self, b_value):
            print("Initialize the new instance of B.")
            self.b_value = b_value
    
    7, which allow for passing an undefined number of initialization arguments to the underlying instance.

  • Dòng 5 in một thông báo khi

    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    5 chạy bước tạo đối tượng. prints a message when
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    5 runs the object creation step.

  • Dòng 6 tạo ra một thể hiện

    >>> from point import Point
    
    >>> point = Point.__new__(Point)
    1. Create a new instance of Point.
    
    >>> # The point object is not initialized
    >>> point.x
    Traceback (most recent call last):
        ...
    AttributeError: 'Point' object has no attribute 'x'
    >>> point.y
    Traceback (most recent call last):
        ...
    AttributeError: 'Point' object has no attribute 'y'
    
    >>> point.__init__(21, 42)
    2. Initialize the new instance of Point.
    
    >>> # Now point is properly initialized
    >>> point
    Point(x=21, y=42)
    
    8 mới bằng cách gọi phương thức lớp cha ____ ____35 với
    # ab_classes.py
    
    class A:
        def __init__(self, a_value):
            print("Initialize the new instance of A.")
            self.a_value = a_value
    
    class B:
        def __new__(cls, *args, **kwargs):
            return A(42)
    
        def __init__(self, b_value):
            print("Initialize the new instance of B.")
            self.b_value = b_value
    
    4 làm đối số. Trong ví dụ này,
    >>> from ab_classes import B
    
    >>> b = B(21)
    Initialize the new instance of A.
    
    >>> b.b_value
    Traceback (most recent call last):
        ...
    AttributeError: 'A' object has no attribute 'b_value'
    
    >>> isinstance(b, B)
    False
    >>> isinstance(b, A)
    True
    
    >>> b.a_value
    42
    
    2 là lớp cha và cuộc gọi đến
    >>> from ab_classes import B
    
    >>> b = B(21)
    Initialize the new instance of A.
    
    >>> b.b_value
    Traceback (most recent call last):
        ...
    AttributeError: 'A' object has no attribute 'b_value'
    
    >>> isinstance(b, B)
    False
    >>> isinstance(b, A)
    True
    
    >>> b.a_value
    42
    
    3 cho phép bạn truy cập vào nó. Sau đó, ví dụ được trả lại. Trường hợp này sẽ là đối số đầu tiên cho
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    4.
    creates a new
    >>> from point import Point
    
    >>> point = Point.__new__(Point)
    1. Create a new instance of Point.
    
    >>> # The point object is not initialized
    >>> point.x
    Traceback (most recent call last):
        ...
    AttributeError: 'Point' object has no attribute 'x'
    >>> point.y
    Traceback (most recent call last):
        ...
    AttributeError: 'Point' object has no attribute 'y'
    
    >>> point.__init__(21, 42)
    2. Initialize the new instance of Point.
    
    >>> # Now point is properly initialized
    >>> point
    Point(x=21, y=42)
    
    8 instance by calling the parent class’s
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    5 method with
    # ab_classes.py
    
    class A:
        def __init__(self, a_value):
            print("Initialize the new instance of A.")
            self.a_value = a_value
    
    class B:
        def __new__(cls, *args, **kwargs):
            return A(42)
    
        def __init__(self, b_value):
            print("Initialize the new instance of B.")
            self.b_value = b_value
    
    4 as an argument. In this example,
    >>> from ab_classes import B
    
    >>> b = B(21)
    Initialize the new instance of A.
    
    >>> b.b_value
    Traceback (most recent call last):
        ...
    AttributeError: 'A' object has no attribute 'b_value'
    
    >>> isinstance(b, B)
    False
    >>> isinstance(b, A)
    True
    
    >>> b.a_value
    42
    
    2 is the parent class, and the call to
    >>> from ab_classes import B
    
    >>> b = B(21)
    Initialize the new instance of A.
    
    >>> b.b_value
    Traceback (most recent call last):
        ...
    AttributeError: 'A' object has no attribute 'b_value'
    
    >>> isinstance(b, B)
    False
    >>> isinstance(b, A)
    True
    
    >>> b.a_value
    42
    
    3 gives you access to it. Then the instance is returned. This instance will be the first argument to
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    4.

  • Dòng 8 xác định

    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    4, chịu trách nhiệm cho bước khởi tạo. Phương thức này có một đối số đầu tiên gọi là
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    1, giữ một tham chiếu đến thể hiện hiện tại. Phương pháp này cũng có hai đối số bổ sung,
    >>> from ab_classes import B
    
    >>> b = B(21)
    Initialize the new instance of A.
    
    >>> b.b_value
    Traceback (most recent call last):
        ...
    AttributeError: 'A' object has no attribute 'b_value'
    
    >>> isinstance(b, B)
    False
    >>> isinstance(b, A)
    True
    
    >>> b.a_value
    42
    
    7 và
    >>> from ab_classes import B
    
    >>> b = B(21)
    Initialize the new instance of A.
    
    >>> b.b_value
    Traceback (most recent call last):
        ...
    AttributeError: 'A' object has no attribute 'b_value'
    
    >>> isinstance(b, B)
    False
    >>> isinstance(b, A)
    True
    
    >>> b.a_value
    42
    
    8. Các đối số này giữ các giá trị ban đầu cho các thuộc tính thể hiện
    >>> from ab_classes import B
    
    >>> b = B(21)
    Initialize the new instance of A.
    
    >>> b.b_value
    Traceback (most recent call last):
        ...
    AttributeError: 'A' object has no attribute 'b_value'
    
    >>> isinstance(b, B)
    False
    >>> isinstance(b, A)
    True
    
    >>> b.a_value
    42
    
    9 và
    >>> class Rectangle:
    ...     def __init__(self, width, height):
    ...         self.width = width
    ...         self.height = height
    ...
    
    >>> rectangle = Rectangle(21, 42)
    >>> rectangle.width
    21
    >>> rectangle.height
    42
    
    0. Bạn cần phải vượt qua các giá trị phù hợp cho các đối số này trong cuộc gọi đến
    >>> class Rectangle:
    ...     def __init__(self, width, height):
    ...         self.width = width
    ...         self.height = height
    ...
    
    >>> rectangle = Rectangle(21, 42)
    >>> rectangle.width
    21
    >>> rectangle.height
    42
    
    1, như bạn sẽ học trong giây lát.
    defines
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    4, which is responsible for the initialization step. This method takes a first argument called
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    1, which holds a reference to the current instance. The method also takes two additional arguments,
    >>> from ab_classes import B
    
    >>> b = B(21)
    Initialize the new instance of A.
    
    >>> b.b_value
    Traceback (most recent call last):
        ...
    AttributeError: 'A' object has no attribute 'b_value'
    
    >>> isinstance(b, B)
    False
    >>> isinstance(b, A)
    True
    
    >>> b.a_value
    42
    
    7 and
    >>> from ab_classes import B
    
    >>> b = B(21)
    Initialize the new instance of A.
    
    >>> b.b_value
    Traceback (most recent call last):
        ...
    AttributeError: 'A' object has no attribute 'b_value'
    
    >>> isinstance(b, B)
    False
    >>> isinstance(b, A)
    True
    
    >>> b.a_value
    42
    
    8. These arguments hold initial values for the instance attributes
    >>> from ab_classes import B
    
    >>> b = B(21)
    Initialize the new instance of A.
    
    >>> b.b_value
    Traceback (most recent call last):
        ...
    AttributeError: 'A' object has no attribute 'b_value'
    
    >>> isinstance(b, B)
    False
    >>> isinstance(b, A)
    True
    
    >>> b.a_value
    42
    
    9 and
    >>> class Rectangle:
    ...     def __init__(self, width, height):
    ...         self.width = width
    ...         self.height = height
    ...
    
    >>> rectangle = Rectangle(21, 42)
    >>> rectangle.width
    21
    >>> rectangle.height
    42
    
    0. You need to pass suitable values for these arguments in the call to
    >>> class Rectangle:
    ...     def __init__(self, width, height):
    ...         self.width = width
    ...         self.height = height
    ...
    
    >>> rectangle = Rectangle(21, 42)
    >>> rectangle.width
    21
    >>> rectangle.height
    42
    
    1, as you’ll learn in a moment.

  • Dòng 9 in một thông báo khi

    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    4 chạy bước khởi tạo đối tượng. prints a message when
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    4 runs the object initialization step.

  • Các dòng 10 và 11 khởi tạo tương ứng

    >>> from ab_classes import B
    
    >>> b = B(21)
    Initialize the new instance of A.
    
    >>> b.b_value
    Traceback (most recent call last):
        ...
    AttributeError: 'A' object has no attribute 'b_value'
    
    >>> isinstance(b, B)
    False
    >>> isinstance(b, A)
    True
    
    >>> b.a_value
    42
    
    9 và
    >>> class Rectangle:
    ...     def __init__(self, width, height):
    ...         self.width = width
    ...         self.height = height
    ...
    
    >>> rectangle = Rectangle(21, 42)
    >>> rectangle.width
    21
    >>> rectangle.height
    42
    
    0. Để làm điều này, họ sử dụng các đối số đầu vào được cung cấp
    >>> from ab_classes import B
    
    >>> b = B(21)
    Initialize the new instance of A.
    
    >>> b.b_value
    Traceback (most recent call last):
        ...
    AttributeError: 'A' object has no attribute 'b_value'
    
    >>> isinstance(b, B)
    False
    >>> isinstance(b, A)
    True
    
    >>> b.a_value
    42
    
    7 và
    >>> from ab_classes import B
    
    >>> b = B(21)
    Initialize the new instance of A.
    
    >>> b.b_value
    Traceback (most recent call last):
        ...
    AttributeError: 'A' object has no attribute 'b_value'
    
    >>> isinstance(b, B)
    False
    >>> isinstance(b, A)
    True
    
    >>> b.a_value
    42
    
    8.
    initialize
    >>> from ab_classes import B
    
    >>> b = B(21)
    Initialize the new instance of A.
    
    >>> b.b_value
    Traceback (most recent call last):
        ...
    AttributeError: 'A' object has no attribute 'b_value'
    
    >>> isinstance(b, B)
    False
    >>> isinstance(b, A)
    True
    
    >>> b.a_value
    42
    
    9 and
    >>> class Rectangle:
    ...     def __init__(self, width, height):
    ...         self.width = width
    ...         self.height = height
    ...
    
    >>> rectangle = Rectangle(21, 42)
    >>> rectangle.width
    21
    >>> rectangle.height
    42
    
    0, respectively. To do this, they use the provided input arguments
    >>> from ab_classes import B
    
    >>> b = B(21)
    Initialize the new instance of A.
    
    >>> b.b_value
    Traceback (most recent call last):
        ...
    AttributeError: 'A' object has no attribute 'b_value'
    
    >>> isinstance(b, B)
    False
    >>> isinstance(b, A)
    True
    
    >>> b.a_value
    42
    
    7 and
    >>> from ab_classes import B
    
    >>> b = B(21)
    Initialize the new instance of A.
    
    >>> b.b_value
    Traceback (most recent call last):
        ...
    AttributeError: 'A' object has no attribute 'b_value'
    
    >>> isinstance(b, B)
    False
    >>> isinstance(b, A)
    True
    
    >>> b.a_value
    42
    
    8.

  • Các dòng 13 và 14 thực hiện phương pháp đặc biệt

    >>> class Rectangle:
    ...     def __init__(self, width, height):
    ...         self.width = width
    ...         self.height = height
    ...
    
    >>> rectangle = Rectangle(21, 42)
    >>> rectangle.width
    21
    >>> rectangle.height
    42
    
    7, cung cấp một biểu diễn chuỗi phù hợp cho lớp
    >>> from point import Point
    
    >>> point = Point.__new__(Point)
    1. Create a new instance of Point.
    
    >>> # The point object is not initialized
    >>> point.x
    Traceback (most recent call last):
        ...
    AttributeError: 'Point' object has no attribute 'x'
    >>> point.y
    Traceback (most recent call last):
        ...
    AttributeError: 'Point' object has no attribute 'y'
    
    >>> point.__init__(21, 42)
    2. Initialize the new instance of Point.
    
    >>> # Now point is properly initialized
    >>> point
    Point(x=21, y=42)
    
    8 của bạn.
    implement the
    >>> class Rectangle:
    ...     def __init__(self, width, height):
    ...         self.width = width
    ...         self.height = height
    ...
    
    >>> rectangle = Rectangle(21, 42)
    >>> rectangle.width
    21
    >>> rectangle.height
    42
    
    7 special method, which provides a proper string representation for your
    >>> from point import Point
    
    >>> point = Point.__new__(Point)
    1. Create a new instance of Point.
    
    >>> # The point object is not initialized
    >>> point.x
    Traceback (most recent call last):
        ...
    AttributeError: 'Point' object has no attribute 'x'
    >>> point.y
    Traceback (most recent call last):
        ...
    AttributeError: 'Point' object has no attribute 'y'
    
    >>> point.__init__(21, 42)
    2. Initialize the new instance of Point.
    
    >>> # Now point is properly initialized
    >>> point
    Point(x=21, y=42)
    
    8 class.

Với

>>> from point import Point

>>> point = Point.__new__(Point)
1. Create a new instance of Point.

>>> # The point object is not initialized
>>> point.x
Traceback (most recent call last):
    ...
AttributeError: 'Point' object has no attribute 'x'
>>> point.y
Traceback (most recent call last):
    ...
AttributeError: 'Point' object has no attribute 'y'

>>> point.__init__(21, 42)
2. Initialize the new instance of Point.

>>> # Now point is properly initialized
>>> point
Point(x=21, y=42)
8 tại chỗ, bạn có thể khám phá cách quá trình khởi tạo hoạt động trong thực tế. Lưu mã của bạn vào một tệp có tên
>>> class Rectangle:
...     def __init__(self, width, height):
...         self.width = width
...         self.height = height
...         return 42
...

>>> rectangle = Rectangle(21, 42)
Traceback (most recent call last):
    ...
TypeError: __init__() should return None, not 'int'
0 và bắt đầu trình thông dịch Python của bạn trong cửa sổ dòng lệnh. Sau đó chạy mã sau:

>>>

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)

Gọi Trình xây dựng lớp

>>> class Rectangle:
...     def __init__(self, width, height):
...         self.width = width
...         self.height = height
...

>>> rectangle = Rectangle(21, 42)
>>> rectangle.width
21
>>> rectangle.height
42
1 tạo, khởi tạo và trả về một thể hiện mới của lớp. Trường hợp này sau đó được gán cho biến
>>> class Rectangle:
...     def __init__(self, width, height):
...         self.width = width
...         self.height = height
...         return 42
...

>>> rectangle = Rectangle(21, 42)
Traceback (most recent call last):
    ...
TypeError: __init__() should return None, not 'int'
2.

Trong ví dụ này, cuộc gọi đến hàm tạo cũng cho bạn biết các bước mà Python chạy nội bộ chạy để xây dựng thể hiện. Đầu tiên, Python gọi

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
5 và sau đó
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4, dẫn đến một phiên bản mới và được khởi tạo hoàn toàn là
>>> from point import Point

>>> point = Point.__new__(Point)
1. Create a new instance of Point.

>>> # The point object is not initialized
>>> point.x
Traceback (most recent call last):
    ...
AttributeError: 'Point' object has no attribute 'x'
>>> point.y
Traceback (most recent call last):
    ...
AttributeError: 'Point' object has no attribute 'y'

>>> point.__init__(21, 42)
2. Initialize the new instance of Point.

>>> # Now point is properly initialized
>>> point
Point(x=21, y=42)
8, như bạn đã xác nhận ở cuối ví dụ.

Để tiếp tục tìm hiểu về sự khởi tạo của lớp trong Python, bạn có thể thử chạy cả hai bước theo cách thủ công:

>>>

>>> from point import Point

>>> point = Point.__new__(Point)
1. Create a new instance of Point.

>>> # The point object is not initialized
>>> point.x
Traceback (most recent call last):
    ...
AttributeError: 'Point' object has no attribute 'x'
>>> point.y
Traceback (most recent call last):
    ...
AttributeError: 'Point' object has no attribute 'y'

>>> point.__init__(21, 42)
2. Initialize the new instance of Point.

>>> # Now point is properly initialized
>>> point
Point(x=21, y=42)

Gọi Trình xây dựng lớp

>>> class Rectangle:
...     def __init__(self, width, height):
...         self.width = width
...         self.height = height
...

>>> rectangle = Rectangle(21, 42)
>>> rectangle.width
21
>>> rectangle.height
42
1 tạo, khởi tạo và trả về một thể hiện mới của lớp. Trường hợp này sau đó được gán cho biến
>>> class Rectangle:
...     def __init__(self, width, height):
...         self.width = width
...         self.height = height
...         return 42
...

>>> rectangle = Rectangle(21, 42)
Traceback (most recent call last):
    ...
TypeError: __init__() should return None, not 'int'
2.

Trong ví dụ này, cuộc gọi đến hàm tạo cũng cho bạn biết các bước mà Python chạy nội bộ chạy để xây dựng thể hiện. Đầu tiên, Python gọi

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
5 và sau đó
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4, dẫn đến một phiên bản mới và được khởi tạo hoàn toàn là
>>> from point import Point

>>> point = Point.__new__(Point)
1. Create a new instance of Point.

>>> # The point object is not initialized
>>> point.x
Traceback (most recent call last):
    ...
AttributeError: 'Point' object has no attribute 'x'
>>> point.y
Traceback (most recent call last):
    ...
AttributeError: 'Point' object has no attribute 'y'

>>> point.__init__(21, 42)
2. Initialize the new instance of Point.

>>> # Now point is properly initialized
>>> point
Point(x=21, y=42)
8, như bạn đã xác nhận ở cuối ví dụ.

Để tiếp tục tìm hiểu về sự khởi tạo của lớp trong Python, bạn có thể thử chạy cả hai bước theo cách thủ công:

Trong ví dụ này, trước tiên bạn gọi

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
5 trên lớp
>>> from point import Point

>>> point = Point.__new__(Point)
1. Create a new instance of Point.

>>> # The point object is not initialized
>>> point.x
Traceback (most recent call last):
    ...
AttributeError: 'Point' object has no attribute 'x'
>>> point.y
Traceback (most recent call last):
    ...
AttributeError: 'Point' object has no attribute 'y'

>>> point.__init__(21, 42)
2. Initialize the new instance of Point.

>>> # Now point is properly initialized
>>> point
Point(x=21, y=42)
8 của bạn, chuyển bản thân lớp là đối số đầu tiên cho phương thức. Cuộc gọi này chỉ chạy bước đầu tiên của quá trình khởi tạo, tạo một đối tượng mới và trống. Lưu ý rằng việc tạo một thể hiện theo cách này bỏ qua cuộc gọi đến
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4.

# ab_classes.py

class A:
    def __init__(self, a_value):
        print("Initialize the new instance of A.")
        self.a_value = a_value

class B:
    def __new__(cls, *args, **kwargs):
        return A(42)

    def __init__(self, b_value):
        print("Initialize the new instance of B.")
        self.b_value = b_value

Khi bạn có đối tượng mới, thì bạn có thể khởi tạo nó bằng cách gọi

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4 với một tập hợp các đối số thích hợp. Sau cuộc gọi này, đối tượng
>>> from point import Point

>>> point = Point.__new__(Point)
1. Create a new instance of Point.

>>> # The point object is not initialized
>>> point.x
Traceback (most recent call last):
    ...
AttributeError: 'Point' object has no attribute 'x'
>>> point.y
Traceback (most recent call last):
    ...
AttributeError: 'Point' object has no attribute 'y'

>>> point.__init__(21, 42)
2. Initialize the new instance of Point.

>>> # Now point is properly initialized
>>> point
Point(x=21, y=42)
8 của bạn được khởi tạo đúng, với tất cả các thuộc tính của nó được thiết lập.

>>>

>>> from ab_classes import B

>>> b = B(21)
Initialize the new instance of A.

>>> b.b_value
Traceback (most recent call last):
    ...
AttributeError: 'A' object has no attribute 'b_value'

>>> isinstance(b, B)
False
>>> isinstance(b, A)
True

>>> b.a_value
42

Gọi Trình xây dựng lớp

>>> class Rectangle:
...     def __init__(self, width, height):
...         self.width = width
...         self.height = height
...

>>> rectangle = Rectangle(21, 42)
>>> rectangle.width
21
>>> rectangle.height
42
1 tạo, khởi tạo và trả về một thể hiện mới của lớp. Trường hợp này sau đó được gán cho biến
>>> class Rectangle:
...     def __init__(self, width, height):
...         self.width = width
...         self.height = height
...         return 42
...

>>> rectangle = Rectangle(21, 42)
Traceback (most recent call last):
    ...
TypeError: __init__() should return None, not 'int'
2.

Trong ví dụ này, cuộc gọi đến hàm tạo cũng cho bạn biết các bước mà Python chạy nội bộ chạy để xây dựng thể hiện. Đầu tiên, Python gọi

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
5 và sau đó
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4, dẫn đến một phiên bản mới và được khởi tạo hoàn toàn là
>>> from point import Point

>>> point = Point.__new__(Point)
1. Create a new instance of Point.

>>> # The point object is not initialized
>>> point.x
Traceback (most recent call last):
    ...
AttributeError: 'Point' object has no attribute 'x'
>>> point.y
Traceback (most recent call last):
    ...
AttributeError: 'Point' object has no attribute 'y'

>>> point.__init__(21, 42)
2. Initialize the new instance of Point.

>>> # Now point is properly initialized
>>> point
Point(x=21, y=42)
8, như bạn đã xác nhận ở cuối ví dụ.

Để tiếp tục tìm hiểu về sự khởi tạo của lớp trong Python, bạn có thể thử chạy cả hai bước theo cách thủ công:

Trong Python, phương thức

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4 có lẽ là phương pháp đặc biệt phổ biến nhất mà bạn sẽ ghi đè trong các lớp tùy chỉnh của mình. Hầu như tất cả các lớp của bạn sẽ cần triển khai tùy chỉnh
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4. Ghi đè phương thức này sẽ cho phép bạn khởi tạo các đối tượng của mình đúng cách.

Mục đích của bước khởi tạo này là để các đối tượng mới của bạn ở trạng thái hợp lệ để bạn có thể bắt đầu sử dụng chúng ngay trong mã của mình. Trong phần này, bạn sẽ tìm hiểu những điều cơ bản của việc viết các phương thức

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4 của riêng bạn và cách chúng có thể giúp bạn tùy chỉnh các lớp học của mình.

Cung cấp bộ khởi tạo đối tượng tùy chỉnh

Việc triển khai xương trần nhất của

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4 mà bạn có thể viết sẽ chỉ quan tâm đến việc gán các đối số đầu vào cho các thuộc tính thể hiện phù hợp. Ví dụ: giả sử bạn viết một lớp
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
16 yêu cầu các thuộc tính
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
17 và
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
18. Trong trường hợp đó, bạn có thể làm một cái gì đó như thế này:

>>>

>>> class Rectangle:
...     def __init__(self, width, height):
...         self.width = width
...         self.height = height
...

>>> rectangle = Rectangle(21, 42)
>>> rectangle.width
21
>>> rectangle.height
42

Như bạn đã biết trước đây,

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4 chạy bước thứ hai của quá trình khởi tạo đối tượng trong Python. Đối số đầu tiên của nó,
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
1, giữ thể hiện mới xuất phát từ việc gọi
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
5. Phần còn lại của các đối số cho
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4 thường được sử dụng để khởi tạo các thuộc tính thể hiện. Trong ví dụ trên, bạn đã khởi tạo hình chữ nhật
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
17 và
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
18 bằng cách sử dụng các đối số
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
25 và
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
26 cho
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4.

Điều quan trọng cần lưu ý là, mà không cần đếm

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
1, các đối số cho
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4 là những điều tương tự mà bạn đã chuyển trong cuộc gọi cho hàm tạo lớp. Vì vậy, theo một cách nào đó, chữ ký
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4 xác định chữ ký của hàm tạo lớp.

Ngoài ra, hãy nhớ rằng

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4 không được trả lại rõ ràng bất cứ điều gì khác với
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
32 hoặc bạn sẽ nhận được ngoại lệ
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
33:

>>>

>>> class Rectangle:
...     def __init__(self, width, height):
...         self.width = width
...         self.height = height
...         return 42
...

>>> rectangle = Rectangle(21, 42)
Traceback (most recent call last):
    ...
TypeError: __init__() should return None, not 'int'

Như bạn đã biết trước đây,

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4 chạy bước thứ hai của quá trình khởi tạo đối tượng trong Python. Đối số đầu tiên của nó,
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
1, giữ thể hiện mới xuất phát từ việc gọi
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
5. Phần còn lại của các đối số cho
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4 thường được sử dụng để khởi tạo các thuộc tính thể hiện. Trong ví dụ trên, bạn đã khởi tạo hình chữ nhật
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
17 và
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
18 bằng cách sử dụng các đối số
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
25 và
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
26 cho
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4.

Điều quan trọng cần lưu ý là, mà không cần đếm

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
1, các đối số cho
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4 là những điều tương tự mà bạn đã chuyển trong cuộc gọi cho hàm tạo lớp. Vì vậy, theo một cách nào đó, chữ ký
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4 xác định chữ ký của hàm tạo lớp.

Ngoài ra, hãy nhớ rằng

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4 không được trả lại rõ ràng bất cứ điều gì khác với
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
32 hoặc bạn sẽ nhận được ngoại lệ
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
33:

Trong ví dụ này, phương thức

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4 cố gắng trả về một số nguyên, cuối cùng sẽ tăng ngoại lệ
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
33 tại thời gian chạy.

>>>

>>> class Rectangle:
...     def __init__(self, width, height):
...         if not (isinstance(width, (int, float)) and width > 0):
...             raise ValueError(f"positive width expected, got {width}")
...         self.width = width
...         if not (isinstance(height, (int, float)) and height > 0):
...             raise ValueError(f"positive height expected, got {height}")
...         self.height = height
...

>>> rectangle = Rectangle(-21, 42)
Traceback (most recent call last):
    ...
ValueError: positive width expected, got -21

Như bạn đã biết trước đây,

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4 chạy bước thứ hai của quá trình khởi tạo đối tượng trong Python. Đối số đầu tiên của nó,
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
1, giữ thể hiện mới xuất phát từ việc gọi
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
5. Phần còn lại của các đối số cho
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4 thường được sử dụng để khởi tạo các thuộc tính thể hiện. Trong ví dụ trên, bạn đã khởi tạo hình chữ nhật
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
17 và
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
18 bằng cách sử dụng các đối số
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
25 và
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
26 cho
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4.

Điều quan trọng cần lưu ý là, mà không cần đếm

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
1, các đối số cho
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4 là những điều tương tự mà bạn đã chuyển trong cuộc gọi cho hàm tạo lớp. Vì vậy, theo một cách nào đó, chữ ký
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4 xác định chữ ký của hàm tạo lớp.

>>>

>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
0

Như bạn đã biết trước đây,

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4 chạy bước thứ hai của quá trình khởi tạo đối tượng trong Python. Đối số đầu tiên của nó,
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
1, giữ thể hiện mới xuất phát từ việc gọi
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
5. Phần còn lại của các đối số cho
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4 thường được sử dụng để khởi tạo các thuộc tính thể hiện. Trong ví dụ trên, bạn đã khởi tạo hình chữ nhật
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
17 và
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
18 bằng cách sử dụng các đối số
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
25 và
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
26 cho
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4.

Điều quan trọng cần lưu ý là, mà không cần đếm

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
1, các đối số cho
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4 là những điều tương tự mà bạn đã chuyển trong cuộc gọi cho hàm tạo lớp. Vì vậy, theo một cách nào đó, chữ ký
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4 xác định chữ ký của hàm tạo lớp.

Ngoài ra, hãy nhớ rằng >>> from point import Point >>> point = Point(21, 42) 1. Create a new instance of Point. 2. Initialize the new instance of Point. >>> point Point(x=21, y=42) 4 không được trả lại rõ ràng bất cứ điều gì khác với >>> class SomeClass: ... pass ... >>> # Call the class to construct an object >>> SomeClass() <__main__.SomeClass object at 0x7fecf442a140> 32 hoặc bạn sẽ nhận được ngoại lệ >>> class SomeClass: ... pass ... >>> # Call the class to construct an object >>> SomeClass() <__main__.SomeClass object at 0x7fecf442a140> 33:

Trong ví dụ này, phương thức

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4 cố gắng trả về một số nguyên, cuối cùng sẽ tăng ngoại lệ
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
33 tại thời gian chạy.

Thông báo lỗi trong ví dụ trên nói rằng

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4 sẽ trả về
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
32. Tuy nhiên, bạn không cần phải trả lại
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
32 một cách rõ ràng, bởi vì các phương thức và chức năng mà không có tuyên bố
 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
8 rõ ràng chỉ trả về
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
32 hoàn toàn trong Python.

>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
1

Trong ví dụ này,

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4 có một đối số thường xuyên gọi là
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
60. Nó cũng có một đối số tùy chọn gọi là
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
72, mặc định là
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
73. Vì
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
72 có giá trị mặc định, bạn có thể xây dựng các đối tượng bằng cách dựa vào giá trị này hoặc bằng cách cung cấp của riêng bạn.

Hành vi cuối cùng của lớp sẽ phụ thuộc vào giá trị của

>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
72. Nếu đối số này là
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
73, thì bạn sẽ nhận được một lời chào không chính thức khi bạn gọi
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
77. Nếu không, bạn sẽ nhận được một lời chào chính thức hơn.

Để thử

>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
69, hãy tiếp tục và lưu mã vào tệp
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
79. Sau đó mở một phiên tương tác trong thư mục làm việc của bạn và chạy mã sau:

>>>

>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
2

Trong ví dụ đầu tiên, bạn tạo một đối tượng

>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
80 bằng cách chuyển một giá trị cho đối số
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
60 và dựa vào giá trị mặc định là
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
72. Bạn nhận được một lời chào không chính thức trên màn hình của bạn khi bạn gọi
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
77 trên đối tượng
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
80.

Trong ví dụ thứ hai, bạn sử dụng đối số

>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
60 và
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
72 để khởi tạo
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
69. Bởi vì
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
72 là
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
89, kết quả của việc gọi
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
77 là một lời chào chính thức.

Mặc dù đây là một ví dụ đồ chơi, nhưng nó hiển thị cách các giá trị đối số mặc định là một tính năng Python mạnh mẽ mà bạn có thể sử dụng để viết các bộ khởi tạo linh hoạt cho các lớp của mình. Các bộ khởi tạo này sẽ cho phép bạn khởi tạo các lớp của mình bằng các bộ đối số khác nhau tùy thuộc vào nhu cầu của bạn.

Được chứ! Bây giờ bạn đã biết những điều cơ bản của

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4 và bước khởi tạo đối tượng, đó là thời gian để thay đổi bánh răng và bắt đầu lặn sâu hơn vào
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
5 và bước tạo đối tượng.

Tạo đối tượng với >>> from point import Point >>> point = Point(21, 42) 1. Create a new instance of Point. 2. Initialize the new instance of Point. >>> point Point(x=21, y=42) 5

Khi viết các lớp Python, bạn thường không cần phải cung cấp phương pháp đặc biệt của riêng bạn. Hầu hết thời gian, việc triển khai cơ sở từ lớp

>>> from ab_classes import B

>>> b = B(21)
Initialize the new instance of A.

>>> b.b_value
Traceback (most recent call last):
    ...
AttributeError: 'A' object has no attribute 'b_value'

>>> isinstance(b, B)
False
>>> isinstance(b, A)
True

>>> b.a_value
42
2 tích hợp là đủ để xây dựng một đối tượng trống của lớp hiện tại của bạn.

Tuy nhiên, có một vài trường hợp sử dụng thú vị cho phương pháp này. Ví dụ: bạn có thể sử dụng

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
5 để tạo các lớp con của các loại bất biến, chẳng hạn như
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
97,
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
98,
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
99 và
 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
00.

Trong các phần sau, bạn sẽ học cách viết các triển khai tùy chỉnh của

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
5 trong các lớp học của mình. Để làm điều này, bạn sẽ mã hóa một vài ví dụ mà mà sẽ cung cấp cho bạn ý tưởng khi nào bạn có thể cần phải ghi đè phương thức này.

Cung cấp người tạo đối tượng tùy chỉnh

Thông thường, bạn sẽ chỉ viết một triển khai tùy chỉnh

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
5 chỉ khi bạn cần kiểm soát việc tạo một thể hiện mới ở mức thấp. Bây giờ, nếu bạn cần thực hiện tùy chỉnh của phương thức này, thì bạn nên làm theo một vài bước:

  1. Tạo một thể hiện mới bằng cách gọi
     1# point.py
     2
     3class Point:
     4    def __new__(cls, *args, **kwargs):
     5        print("1. Create a new instance of Point.")
     6        return super().__new__(cls)
     7
     8    def __init__(self, x, y):
     9        print("2. Initialize the new instance of Point.")
    10        self.x = x
    11        self.y = y
    12
    13    def __repr__(self) -> str:
    14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
    
    03 với các đối số thích hợp.
    by calling
     1# point.py
     2
     3class Point:
     4    def __new__(cls, *args, **kwargs):
     5        print("1. Create a new instance of Point.")
     6        return super().__new__(cls)
     7
     8    def __init__(self, x, y):
     9        print("2. Initialize the new instance of Point.")
    10        self.x = x
    11        self.y = y
    12
    13    def __repr__(self) -> str:
    14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
    
    03 with appropriate arguments.
  2. Tùy chỉnh phiên bản mới theo nhu cầu cụ thể của bạn. according to your specific needs.
  3. Trả về thể hiện mới để tiếp tục quá trình khởi tạo. to continue the instantiation process.

Với ba bước ngắn gọn này, bạn sẽ có thể tùy chỉnh bước tạo thể hiện trong quá trình khởi tạo Python. Dưới đây, một ví dụ về cách bạn có thể dịch các bước này thành mã Python:

>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
3

Ví dụ này cung cấp một loại triển khai mẫu của

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
5. Như thường lệ,
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
5 lấy lớp hiện tại làm đối số mà thường gọi là
# ab_classes.py

class A:
    def __init__(self, a_value):
        print("Initialize the new instance of A.")
        self.a_value = a_value

class B:
    def __new__(cls, *args, **kwargs):
        return A(42)

    def __init__(self, b_value):
        print("Initialize the new instance of B.")
        self.b_value = b_value
4.

Lưu ý rằng bạn sử dụng

# ab_classes.py

class A:
    def __init__(self, a_value):
        print("Initialize the new instance of A.")
        self.a_value = a_value

class B:
    def __new__(cls, *args, **kwargs):
        return A(42)

    def __init__(self, b_value):
        print("Initialize the new instance of B.")
        self.b_value = b_value
6 và
# ab_classes.py

class A:
    def __init__(self, a_value):
        print("Initialize the new instance of A.")
        self.a_value = a_value

class B:
    def __new__(cls, *args, **kwargs):
        return A(42)

    def __init__(self, b_value):
        print("Initialize the new instance of B.")
        self.b_value = b_value
7 để làm cho phương pháp linh hoạt và có thể duy trì hơn bằng cách chấp nhận bất kỳ số lượng đối số nào. Bạn phải luôn luôn xác định
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
5 với
# ab_classes.py

class A:
    def __init__(self, a_value):
        print("Initialize the new instance of A.")
        self.a_value = a_value

class B:
    def __new__(cls, *args, **kwargs):
        return A(42)

    def __init__(self, b_value):
        print("Initialize the new instance of B.")
        self.b_value = b_value
6 và
# ab_classes.py

class A:
    def __init__(self, a_value):
        print("Initialize the new instance of A.")
        self.a_value = a_value

class B:
    def __new__(cls, *args, **kwargs):
        return A(42)

    def __init__(self, b_value):
        print("Initialize the new instance of B.")
        self.b_value = b_value
7, trừ khi bạn có lý do chính đáng để theo một mô hình khác.

Trong dòng đầu tiên của

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
5, bạn gọi phương thức lớp cha ____ ____35 để tạo một thể hiện mới và phân bổ bộ nhớ cho nó. Để truy cập phương thức lớp cha ____ ____35, bạn sử dụng hàm
>>> from ab_classes import B

>>> b = B(21)
Initialize the new instance of A.

>>> b.b_value
Traceback (most recent call last):
    ...
AttributeError: 'A' object has no attribute 'b_value'

>>> isinstance(b, B)
False
>>> isinstance(b, A)
True

>>> b.a_value
42
3. Chuỗi cuộc gọi này đưa bạn lên đến
 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
16, đây là triển khai cơ bản của
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
5 cho tất cả các lớp Python.

Bước tiếp theo là tùy chỉnh thể hiện mới được tạo của bạn. Bạn có thể làm bất cứ điều gì bạn cần làm để tùy chỉnh thể hiện trong tay. Cuối cùng, trong bước thứ ba, bạn cần trả về thể hiện mới để tiếp tục quá trình khởi tạo với bước khởi tạo.

Điều quan trọng cần lưu ý là

 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
16 chỉ chấp nhận một đối số duy nhất, lớp để khởi tạo. Nếu bạn gọi
 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
16 với nhiều đối số hơn, thì bạn sẽ nhận được
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
33:

>>>

>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
4

Trong ví dụ đầu tiên, bạn tạo một đối tượng

>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
80 bằng cách chuyển một giá trị cho đối số
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
60 và dựa vào giá trị mặc định là
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
72. Bạn nhận được một lời chào không chính thức trên màn hình của bạn khi bạn gọi
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
77 trên đối tượng
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
80.

Trong ví dụ thứ hai, bạn sử dụng đối số

>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
60 và
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
72 để khởi tạo
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
69. Bởi vì
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
72 là
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
89, kết quả của việc gọi
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
77 là một lời chào chính thức.

>>>

>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
5

Trong việc triển khai

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
7 này, bạn không ghi đè lên
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
5. Việc tạo đối tượng sau đó được giao cho
 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
16, hiện chấp nhận
 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
33 và chuyển nó sang
 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
34 để hoàn thiện việc khởi tạo. Bây giờ bạn có thể tạo các phiên bản mới và được khởi tạo đầy đủ là
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
7, giống như
 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
36 trong ví dụ.

Mát mẻ! Bây giờ bạn đã biết những điều cơ bản của việc viết các triển khai

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
5 của riêng bạn, bạn đã sẵn sàng tìm hiểu một vài ví dụ thực tế có một số trường hợp sử dụng phổ biến nhất của phương pháp này trong lập trình Python.

Các loại tích hợp bất biến

Để khởi động mọi thứ, bạn sẽ bắt đầu với một trường hợp sử dụng là

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
5 bao gồm phân lớp một loại tích hợp bất biến. Ví dụ, giả sử bạn cần viết một lớp
 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
39 dưới dạng một lớp con của loại Python từ ____ ____198. Lớp học của bạn sẽ có một thuộc tính bổ sung để lưu trữ đơn vị mà sử dụng để đo khoảng cách.

Ở đây, một cách tiếp cận đầu tiên cho vấn đề này, sử dụng phương pháp

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4:

>>>

>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
6

Khi bạn phân lớp một kiểu dữ liệu tích hợp bất biến, bạn sẽ gặp lỗi. Một phần của vấn đề là giá trị được đặt trong quá trình tạo và nó quá muộn để thay đổi nó trong quá trình khởi tạo. Ngoài ra,

 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
42 được gọi dưới mui xe và nó không đối phó với các đối số bổ sung theo cách tương tự như
 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
16. Đây là những gì làm tăng lỗi trong ví dụ của bạn.

Để giải quyết vấn đề này, bạn có thể khởi tạo đối tượng tại thời điểm tạo với

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
5 thay vì ghi đè
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4. Đây là cách bạn có thể làm điều này trong thực tế:

>>>

>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
7

Trong ví dụ này,

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
5 chạy ba bước mà bạn đã học trong phần trước. Đầu tiên, phương thức tạo ra một thể hiện mới của lớp hiện tại,
# ab_classes.py

class A:
    def __init__(self, a_value):
        print("Initialize the new instance of A.")
        self.a_value = a_value

class B:
    def __new__(cls, *args, **kwargs):
        return A(42)

    def __init__(self, b_value):
        print("Initialize the new instance of B.")
        self.b_value = b_value
4, bằng cách gọi
 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
03. Lần này, cuộc gọi quay trở lại
 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
42, tạo ra một thể hiện mới và khởi tạo nó bằng cách sử dụng
 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
33 làm đối số. Sau đó, phương thức tùy chỉnh thể hiện mới bằng cách thêm thuộc tính
 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
51 cho nó. Cuối cùng, ví dụ mới được trả lại.

Đó là nó! Bây giờ lớp

 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
39 của bạn hoạt động như mong đợi, cho phép bạn sử dụng thuộc tính thể hiện để lưu trữ thiết bị mà bạn có thể đo khoảng cách. Không giống như giá trị điểm nổi được lưu trữ trong một trường hợp nhất định là
 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
39, thuộc tính
 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
51 có thể thay đổi, do đó bạn có thể thay đổi giá trị của nó bất cứ khi nào bạn muốn. Cuối cùng, lưu ý cách gọi đến chức năng
 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
55 cho thấy lớp của bạn kế thừa các tính năng và phương thức từ
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
98.

Trả lại các trường hợp của một lớp khác

Trả về một đối tượng của một lớp khác là một yêu cầu có thể nâng cao nhu cầu thực hiện tùy chỉnh của

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
5. Tuy nhiên, bạn nên cẩn thận vì trong trường hợp này, Python bỏ qua bước khởi tạo hoàn toàn. Vì vậy, bạn sẽ có trách nhiệm đưa đối tượng mới được tạo vào trạng thái hợp lệ trước khi sử dụng mã trong mã của bạn.

Kiểm tra ví dụ sau, trong đó lớp

 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
58 sử dụng
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
5 để trả về các phiên bản của các lớp được chọn ngẫu nhiên:

>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
8

Trong ví dụ này,

 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
58 cung cấp một phương thức
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
5 tạo ra một thể hiện mới bằng cách chọn ngẫu nhiên một lớp từ danh sách các lớp hiện có.

Tại đây, cách bạn có thể sử dụng lớp

 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
58 này như một nhà máy của các đối tượng thú cưng:

>>>

>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
9

Mỗi khi bạn khởi tạo

 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
58, bạn sẽ nhận được một đối tượng ngẫu nhiên từ một lớp khác. Kết quả này là có thể bởi vì không có hạn chế nào đối với đối tượng mà
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
5 có thể trả về. Sử dụng
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
5 theo cách như vậy biến một lớp thành một nhà máy vật thể linh hoạt và mạnh mẽ, không giới hạn ở các trường hợp của chính nó.

Cuối cùng, lưu ý cách phương thức

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4 của
 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
58 không bao giờ chạy. Điều đó bởi vì
 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
68 luôn trả về các đối tượng của một lớp khác chứ không phải là chính
 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
58.

Chỉ cho phép một trường hợp duy nhất trong các lớp của bạn

Đôi khi bạn cần thực hiện một lớp cho phép tạo một thể hiện duy nhất. Loại lớp này thường được gọi là lớp singleton. Trong tình huống này, phương pháp

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
5 có ích vì nó có thể giúp bạn hạn chế số lượng trường hợp mà một lớp nhất định có thể có.

Ở đây, một ví dụ về mã hóa một lớp

 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
71 với phương thức
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
5 cho phép tạo ra một trường hợp tại một thời điểm. Để làm điều này,
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
5 kiểm tra sự tồn tại của các trường hợp trước được lưu trong bộ nhớ cache trên một thuộc tính lớp:

>>>

 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
0

Lớp

 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
71 trong ví dụ này có thuộc tính lớp có tên
 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
75 mặc định là
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
32 và hoạt động như một bộ đệm. Phương pháp
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
5 kiểm tra nếu không có trường hợp trước đó tồn tại bằng cách kiểm tra điều kiện
 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
78.

Nếu điều kiện này là đúng, thì khối mã

 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
79 sẽ tạo ra một thể hiện mới là
 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
71 và lưu trữ nó đến
 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
81. Cuối cùng, phương thức trả về phiên bản mới hoặc hiện tại cho người gọi.

Sau đó, bạn khởi tạo

 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
71 hai lần để cố gắng xây dựng hai đối tượng khác nhau,
 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
83 và
 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
84. Nếu bạn so sánh danh tính của các đối tượng này với toán tử
 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
85, thì bạn sẽ lưu ý rằng cả hai đối tượng là cùng một đối tượng. Các tên
 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
83 và
 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
84 chỉ giữ các tham chiếu đến cùng một đối tượng
 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
71.

Mô phỏng một phần 1# point.py 2 3class Point: 4 def __new__(cls, *args, **kwargs): 5 print("1. Create a new instance of Point.") 6 return super().__new__(cls) 7 8 def __init__(self, x, y): 9 print("2. Initialize the new instance of Point.") 10 self.x = x 11 self.y = y 12 13 def __repr__(self) -> str: 14 return f"{type(self).__name__}(x={self.x}, y={self.y})" 89

Như một ví dụ cuối cùng về cách tận dụng

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
5 trong mã của bạn, bạn có thể thúc đẩy các kỹ năng Python của mình và viết một chức năng nhà máy mô phỏng một phần
 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
91. Hàm
 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
92 cho phép bạn tạo các lớp con của
>>> class SomeClass:
...     pass
...

>>> # Call the class to construct an object
>>> SomeClass()
<__main__.SomeClass object at 0x7fecf442a140>
99 với tính năng bổ sung là có các trường được đặt tên để truy cập các mục trong tuple.

Mã bên dưới thực hiện hàm

 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
94 mô phỏng một phần chức năng này bằng cách ghi đè phương thức
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
5 của một lớp lồng nhau gọi là
 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
96:

 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
1

Ở đây, cách thức chức năng nhà máy này hoạt động từng dòng:

  • Dòng 3 nhập

     1# point.py
     2
     3class Point:
     4    def __new__(cls, *args, **kwargs):
     5        print("1. Create a new instance of Point.")
     6        return super().__new__(cls)
     7
     8    def __init__(self, x, y):
     9        print("2. Initialize the new instance of Point.")
    10        self.x = x
    11        self.y = y
    12
    13    def __repr__(self) -> str:
    14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
    
    97 từ mô -đun
     1# point.py
     2
     3class Point:
     4    def __new__(cls, *args, **kwargs):
     5        print("1. Create a new instance of Point.")
     6        return super().__new__(cls)
     7
     8    def __init__(self, x, y):
     9        print("2. Initialize the new instance of Point.")
    10        self.x = x
    11        self.y = y
    12
    13    def __repr__(self) -> str:
    14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
    
    98. Hàm này cho phép bạn truy xuất các mục bằng chỉ mục của chúng trong chuỗi chứa.
    imports
     1# point.py
     2
     3class Point:
     4    def __new__(cls, *args, **kwargs):
     5        print("1. Create a new instance of Point.")
     6        return super().__new__(cls)
     7
     8    def __init__(self, x, y):
     9        print("2. Initialize the new instance of Point.")
    10        self.x = x
    11        self.y = y
    12
    13    def __repr__(self) -> str:
    14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
    
    97 from the
     1# point.py
     2
     3class Point:
     4    def __new__(cls, *args, **kwargs):
     5        print("1. Create a new instance of Point.")
     6        return super().__new__(cls)
     7
     8    def __init__(self, x, y):
     9        print("2. Initialize the new instance of Point.")
    10        self.x = x
    11        self.y = y
    12
    13    def __repr__(self) -> str:
    14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
    
    98 module. This function allows you to retrieve items using their index in the containing sequence.

  • Dòng 5 xác định

     1# point.py
     2
     3class Point:
     4    def __new__(cls, *args, **kwargs):
     5        print("1. Create a new instance of Point.")
     6        return super().__new__(cls)
     7
     8    def __init__(self, x, y):
     9        print("2. Initialize the new instance of Point.")
    10        self.x = x
    11        self.y = y
    12
    13    def __repr__(self) -> str:
    14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
    
    94. Hàm này có một đối số đầu tiên gọi là
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    00, sẽ giữ tên của lớp con tuple mà bạn muốn tạo. Đối số
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    01 cho phép bạn vượt qua số lượng tên trường không xác định dưới dạng chuỗi.
    defines
     1# point.py
     2
     3class Point:
     4    def __new__(cls, *args, **kwargs):
     5        print("1. Create a new instance of Point.")
     6        return super().__new__(cls)
     7
     8    def __init__(self, x, y):
     9        print("2. Initialize the new instance of Point.")
    10        self.x = x
    11        self.y = y
    12
    13    def __repr__(self) -> str:
    14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
    
    94. This function takes a first argument called
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    00, which will hold the name of the tuple subclass that you want to create. The
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    01 argument allows you to pass an undefined number of field names as strings.

  • Dòng 6 xác định một biến cục bộ để giữ số lượng các trường được đặt tên do người dùng cung cấp. defines a local variable to hold the number of named fields provided by the user.

  • Dòng 8 xác định một lớp lồng nhau được gọi là

     1# point.py
     2
     3class Point:
     4    def __new__(cls, *args, **kwargs):
     5        print("1. Create a new instance of Point.")
     6        return super().__new__(cls)
     7
     8    def __init__(self, x, y):
     9        print("2. Initialize the new instance of Point.")
    10        self.x = x
    11        self.y = y
    12
    13    def __repr__(self) -> str:
    14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
    
    96, kế thừa từ lớp
    >>> class SomeClass:
    ...     pass
    ...
    
    >>> # Call the class to construct an object
    >>> SomeClass()
    <__main__.SomeClass object at 0x7fecf442a140>
    
    99 tích hợp.
    defines a nested class called
     1# point.py
     2
     3class Point:
     4    def __new__(cls, *args, **kwargs):
     5        print("1. Create a new instance of Point.")
     6        return super().__new__(cls)
     7
     8    def __init__(self, x, y):
     9        print("2. Initialize the new instance of Point.")
    10        self.x = x
    11        self.y = y
    12
    13    def __repr__(self) -> str:
    14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
    
    96, which inherits from the built-in
    >>> class SomeClass:
    ...     pass
    ...
    
    >>> # Call the class to construct an object
    >>> SomeClass()
    <__main__.SomeClass object at 0x7fecf442a140>
    
    99 class.

  • Dòng 9 cung cấp thuộc tính lớp

    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    04. Thuộc tính này xác định một tuple để giữ các thuộc tính thể hiện. Tuple này lưu bộ nhớ bằng cách hoạt động thay thế cho từ điển phiên bản,
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    05, nếu không sẽ đóng một vai trò tương tự.
    provides a
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    04 class attribute. This attribute defines a tuple for holding instance attributes. This tuple saves memory by acting as a substitute for the instance’s dictionary,
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    05, which would otherwise play a similar role.

  • Dòng 11 thực hiện

    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    5 với
    # ab_classes.py
    
    class A:
        def __init__(self, a_value):
            print("Initialize the new instance of A.")
            self.a_value = a_value
    
    class B:
        def __new__(cls, *args, **kwargs):
            return A(42)
    
        def __init__(self, b_value):
            print("Initialize the new instance of B.")
            self.b_value = b_value
    
    4 là đối số đầu tiên của nó. Việc triển khai này cũng có đối số
    # ab_classes.py
    
    class A:
        def __init__(self, a_value):
            print("Initialize the new instance of A.")
            self.a_value = a_value
    
    class B:
        def __new__(cls, *args, **kwargs):
            return A(42)
    
        def __init__(self, b_value):
            print("Initialize the new instance of B.")
            self.b_value = b_value
    
    6 để chấp nhận số lượng giá trị trường không xác định.
    implements
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    5 with
    # ab_classes.py
    
    class A:
        def __init__(self, a_value):
            print("Initialize the new instance of A.")
            self.a_value = a_value
    
    class B:
        def __new__(cls, *args, **kwargs):
            return A(42)
    
        def __init__(self, b_value):
            print("Initialize the new instance of B.")
            self.b_value = b_value
    
    4 as its first argument. This implementation also takes the
    # ab_classes.py
    
    class A:
        def __init__(self, a_value):
            print("Initialize the new instance of A.")
            self.a_value = a_value
    
    class B:
        def __new__(cls, *args, **kwargs):
            return A(42)
    
        def __init__(self, b_value):
            print("Initialize the new instance of B.")
            self.b_value = b_value
    
    6 argument to accept an undefined number of field values.

  • Các dòng 12 đến 16 Xác định một câu lệnh có điều kiện kiểm tra xem số lượng mục để lưu trữ trong phần cuối cùng khác với số trường được đặt tên. Nếu đó là trường hợp, thì điều kiện sẽ tăng

    >>> class SomeClass:
    ...     pass
    ...
    
    >>> # Call the class to construct an object
    >>> SomeClass()
    <__main__.SomeClass object at 0x7fecf442a140>
    
    33 với thông báo lỗi. define a conditional statement that checks if the number of items to store in the final tuple differs from the number of named fields. If that’s the case, then the conditional raises a
    >>> class SomeClass:
    ...     pass
    ...
    
    >>> # Call the class to construct an object
    >>> SomeClass()
    <__main__.SomeClass object at 0x7fecf442a140>
    
    33 with an error message.

  • Dòng 17 Đặt thuộc tính

    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    10 của lớp hiện tại thành giá trị được cung cấp bởi
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    00.
    sets the
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    10 attribute of the current class to the value provided by
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    00.

  • Các dòng 18 và 19 Xác định vòng lặp

    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    12 biến mọi trường được đặt tên thành một thuộc tính sử dụng
     1# point.py
     2
     3class Point:
     4    def __new__(cls, *args, **kwargs):
     5        print("1. Create a new instance of Point.")
     6        return super().__new__(cls)
     7
     8    def __init__(self, x, y):
     9        print("2. Initialize the new instance of Point.")
    10        self.x = x
    11        self.y = y
    12
    13    def __repr__(self) -> str:
    14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
    
    97 để trả lại mục tại mục tiêu
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    14. Vòng lặp sử dụng chức năng
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    15 tích hợp để thực hiện hành động này. Lưu ý rằng hàm
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    16 tích hợp cung cấp giá trị
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    14 thích hợp.
    define a
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    12 loop that turns every named field into a property that uses
     1# point.py
     2
     3class Point:
     4    def __new__(cls, *args, **kwargs):
     5        print("1. Create a new instance of Point.")
     6        return super().__new__(cls)
     7
     8    def __init__(self, x, y):
     9        print("2. Initialize the new instance of Point.")
    10        self.x = x
    11        self.y = y
    12
    13    def __repr__(self) -> str:
    14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
    
    97 to return the item at the target
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    14. The loop uses the built-in
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    15 function to perform this action. Note that the built-in
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    16 function provides the appropriate
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    14 value.

  • Dòng 20 trả về một thể hiện mới của lớp hiện tại bằng cách gọi

     1# point.py
     2
     3class Point:
     4    def __new__(cls, *args, **kwargs):
     5        print("1. Create a new instance of Point.")
     6        return super().__new__(cls)
     7
     8    def __init__(self, x, y):
     9        print("2. Initialize the new instance of Point.")
    10        self.x = x
    11        self.y = y
    12
    13    def __repr__(self) -> str:
    14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
    
    03 như bình thường. returns a new instance of the current class by calling
     1# point.py
     2
     3class Point:
     4    def __new__(cls, *args, **kwargs):
     5        print("1. Create a new instance of Point.")
     6        return super().__new__(cls)
     7
     8    def __init__(self, x, y):
     9        print("2. Initialize the new instance of Point.")
    10        self.x = x
    11        self.y = y
    12
    13    def __repr__(self) -> str:
    14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
    
    03 as usual.

  • Dòng 22 và 23 Xác định phương pháp

    >>> class Rectangle:
    ...     def __init__(self, width, height):
    ...         self.width = width
    ...         self.height = height
    ...
    
    >>> rectangle = Rectangle(21, 42)
    >>> rectangle.width
    21
    >>> rectangle.height
    42
    
    7 cho lớp con Tuple của bạn. define a
    >>> class Rectangle:
    ...     def __init__(self, width, height):
    ...         self.width = width
    ...         self.height = height
    ...
    
    >>> rectangle = Rectangle(21, 42)
    >>> rectangle.width
    21
    >>> rectangle.height
    42
    
    7 method for your tuple subclass.

  • Dòng 25 Trả về lớp

     1# point.py
     2
     3class Point:
     4    def __new__(cls, *args, **kwargs):
     5        print("1. Create a new instance of Point.")
     6        return super().__new__(cls)
     7
     8    def __init__(self, x, y):
     9        print("2. Initialize the new instance of Point.")
    10        self.x = x
    11        self.y = y
    12
    13    def __repr__(self) -> str:
    14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
    
    96 mới được tạo. returns the newly created
     1# point.py
     2
     3class Point:
     4    def __new__(cls, *args, **kwargs):
     5        print("1. Create a new instance of Point.")
     6        return super().__new__(cls)
     7
     8    def __init__(self, x, y):
     9        print("2. Initialize the new instance of Point.")
    10        self.x = x
    11        self.y = y
    12
    13    def __repr__(self) -> str:
    14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
    
    96 class.

Để thử

 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
94 của bạn, hãy kích hoạt một phiên tương tác vào thư mục chứa tệp
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
22 và chạy mã sau:

>>>

 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
2

Trong đoạn mã này, bạn tạo một lớp

>>> from point import Point

>>> point = Point.__new__(Point)
1. Create a new instance of Point.

>>> # The point object is not initialized
>>> point.x
Traceback (most recent call last):
    ...
AttributeError: 'Point' object has no attribute 'x'
>>> point.y
Traceback (most recent call last):
    ...
AttributeError: 'Point' object has no attribute 'y'

>>> point.__init__(21, 42)
2. Initialize the new instance of Point.

>>> # Now point is properly initialized
>>> point
Point(x=21, y=42)
8 mới bằng cách gọi
 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
94. Đối số đầu tiên trong cuộc gọi này thể hiện tên mà đối tượng lớp kết quả sẽ sử dụng. Các đối số thứ hai và thứ ba là các trường được đặt tên có sẵn trong lớp kết quả.

Sau đó, bạn tạo một đối tượng

>>> from point import Point

>>> point = Point.__new__(Point)
1. Create a new instance of Point.

>>> # The point object is not initialized
>>> point.x
Traceback (most recent call last):
    ...
AttributeError: 'Point' object has no attribute 'x'
>>> point.y
Traceback (most recent call last):
    ...
AttributeError: 'Point' object has no attribute 'y'

>>> point.__init__(21, 42)
2. Initialize the new instance of Point.

>>> # Now point is properly initialized
>>> point
Point(x=21, y=42)
8 bằng cách gọi hàm tạo lớp với các giá trị phù hợp cho các trường
>>> from ab_classes import B

>>> b = B(21)
Initialize the new instance of A.

>>> b.b_value
Traceback (most recent call last):
    ...
AttributeError: 'A' object has no attribute 'b_value'

>>> isinstance(b, B)
False
>>> isinstance(b, A)
True

>>> b.a_value
42
9 và
>>> class Rectangle:
...     def __init__(self, width, height):
...         self.width = width
...         self.height = height
...

>>> rectangle = Rectangle(21, 42)
>>> rectangle.width
21
>>> rectangle.height
42
0. Để truy cập giá trị của từng trường được đặt tên, bạn có thể sử dụng ký hiệu dấu chấm. Bạn cũng có thể sử dụng các chỉ số để truy xuất các giá trị vì lớp của bạn là một lớp con Tuple.

Bởi vì các bộ dữ liệu là các loại dữ liệu bất biến trong Python, bạn có thể gán các giá trị mới cho tọa độ điểm tại chỗ. Nếu bạn cố gắng làm điều đó, thì bạn sẽ nhận được

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
28.

Cuối cùng, gọi

 1# point.py
 2
 3class Point:
 4    def __new__(cls, *args, **kwargs):
 5        print("1. Create a new instance of Point.")
 6        return super().__new__(cls)
 7
 8    def __init__(self, x, y):
 9        print("2. Initialize the new instance of Point.")
10        self.x = x
11        self.y = y
12
13    def __repr__(self) -> str:
14        return f"{type(self).__name__}(x={self.x}, y={self.y})"
55 với thể hiện
>>> class Rectangle:
...     def __init__(self, width, height):
...         self.width = width
...         self.height = height
...         return 42
...

>>> rectangle = Rectangle(21, 42)
Traceback (most recent call last):
    ...
TypeError: __init__() should return None, not 'int'
2 của bạn như một đối số cho thấy rằng đối tượng của bạn kế thừa tất cả các thuộc tính và phương thức mà các bộ dữ liệu thông thường có trong Python.

Sự kết luận

Bây giờ bạn đã biết làm thế nào các trình xây dựng lớp Python cho phép bạn khởi tạo các lớp, để bạn có thể tạo các đối tượng cụ thể và sẵn sàng để sử dụng trong mã của mình. Trong Python, các nhà xây dựng lớp kích hoạt nội bộ quá trình khởi tạo hoặc xây dựng, thông qua việc tạo và khởi tạo thể hiện. Các bước này được điều khiển bởi các phương pháp đặc biệt

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
5 và
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4.instance creation and instance initialization. These steps are driven by the
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
5 and
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4 special methods.

Bằng cách tìm hiểu về các trình xây dựng lớp Python, quá trình khởi tạo và các phương thức

>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
5 và
>>> from point import Point

>>> point = Point(21, 42)
1. Create a new instance of Point.
2. Initialize the new instance of Point.

>>> point
Point(x=21, y=42)
4, giờ đây bạn có thể quản lý cách các lớp tùy chỉnh của bạn xây dựng các trường hợp mới.

Trong hướng dẫn này, bạn đã học được:

  • Quá trình khởi tạo Python như thế nào hoạt động trong nội bộinstantiation process works internally
  • Phương pháp
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    4 của riêng bạn giúp bạn tùy chỉnh khởi tạo đối tượng
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    4
    methods help you customize object initialization
  • Cách ghi đè phương thức
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    5 cho phép tạo đối tượng tùy chỉnh
    >>> from point import Point
    
    >>> point = Point(21, 42)
    1. Create a new instance of Point.
    2. Initialize the new instance of Point.
    
    >>> point
    Point(x=21, y=42)
    
    5
    method allows for custom object creation

Bây giờ, bạn đã sẵn sàng để tận dụng kiến thức này để điều chỉnh các trình xây dựng lớp học của bạn và kiểm soát hoàn toàn việc tạo và khởi tạo thể hiện trong cuộc phiêu lưu lập trình hướng đối tượng của bạn với Python.

Xem bây giờ hướng dẫn này có một khóa học video liên quan được tạo bởi nhóm Python thực sự.Xem nó cùng với hướng dẫn bằng văn bản để hiểu sâu hơn về sự hiểu biết của bạn: Sử dụng các trình xây dựng lớp Python This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Using Python Class Constructors