Đối tượng trong đối số lớp Python là gì?

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 hàm tạo của lớp kích hoạt nội bộ quy trình khởi tạo của Python, quy trình này trải qua hai bước chính. tạo cá thể và khởi tạo cá thể

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

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

  • Hiểu quy trình khởi tạo nội bộ của Python
  • 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)
    
    2
  • 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)
    
    3

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 mình, đ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 về các ví dụ và khái niệm trong hướng dẫn này, bạn nên làm quen với lập trình hướng đối tượng và Python

Tiền thưởng miễn phí. Nhấp vào đây để có quyền truy cập vào Bảng cheat Python OOP miễn phí chỉ cho bạn các hướng dẫn, video và sách hay nhất để tìm hiểu thêm về Lập trình hướng đối tượng với Python

Trình xây dựng lớp của Python và quy 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, cho phép bạn xác định các lớp tùy chỉnh có thể có để lưu trữ dữ liệu và cung cấp các 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

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 hoặc khởi tạo đối tượng. 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

Loại bỏ các quảng cáo

Làm quen với các hàm tạo lớp của 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, giống như cách bạn gọi bất kỳ hàm 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)
5 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)
4. 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 đó, phần thân của lớp chỉ chứa một câu lệ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 như một câu lệnh 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)
5 bằng cách gọi lớp bằng một cặp dấu ngoặc đơn. Trong ví dụ này, bạn không cần truyền bất kỳ đối số nào trong cuộc gọi vì lớp của bạn chưa nhận đối số

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

Điểm cuối cùng cần lưu ý là gọi một lớp không giống như gọi một thể hiện của một lớp. Đây là hai chủ đề khác nhau và không liên quan. Để làm cho thể hiện của một lớp có thể gọi được, bạn cần triển khai một phương thức đặc biệt, phương thức này không liên quan gì đến quy trình khởi tạo của Python

Hiểu quy trình khởi tạo của Python

Bạn kích hoạt quy trình khởi tạo của Python bất cứ khi nào bạn gọi một lớp Python để tạo một phiên bản mới. Quá trình này trải qua hai bước riêng biệt mà bạn có thể mô tả như sau

  1. Tạo một thể hiện mới của lớp đích
  2. Khởi tạo phiên bản mới với trạng thái ban đầu phù hợp

Để chạy bước đầu tiên, các lớp Python có một phương thức đặc biệt gọi là , 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 thức đặc biệt khác, 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)
2 lấy đối tượng mới làm đối số đầu tiên của 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)
3. 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 của lớp truyền cho nó

Nói tóm lại, quá trình khởi tạo của Python bắt đầu bằng một lệnh gọi hàm tạo của lớp, lệnh này sẽ kích hoạt trình tạo cá thể,

>>> 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)
3, để 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 cá thể,
>>> 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, lấy các đối số của hàm tạo để khởi tạo đối tượng mới được tạo

Để khám phá cách quy trình khởi tạo của Python hoạt động bên trong, hãy xem xét ví dụ sau về 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)
6 triển khai 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)
3 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)
2, 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 là một sự cố về những gì mã này làm

  • Dòng 3 định nghĩ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)
    
    6 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)
    
    4 theo sau là tên lớp

  • Dòng 4 định nghĩa 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)
    
    3, lấy lớp làm đối số đầu tiên của 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
    
    2 làm tên của đối số này là một quy ước mạnh trong Python, giống như sử dụ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)
    
    3 để đặt tên cho phiên bản hiện tại là. Phương thức này cũng lấy
    # 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 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
    
    5, cho phép chuyển một số lượng đối số khởi tạo không xác định cho đối tượng bên dưới

  • Dòng 5 in 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)
    
    3 chạy bước tạo đối tượng

  • Dòng 6 tạo 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)
    
    6 mới bằng cách gọ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)
    
    3 của lớp cha với đối số 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
    
    2. Trong ví dụ này, là lớp cha và lệnh gọi tới
    >>> 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
    
    1 cho phép bạn truy cập vào nó. Sau đó, ví dụ được trả lại. Ví dụ này sẽ là đối số đầ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)
    
    2

  • Dòng 8 định nghĩ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)
    
    2, chịu trách nhiệm cho bước khởi tạo. Phương thức này lấy đối số đầu tiên có tê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)
    
    3, chứa tham chiếu đến phiên bản hiện tại. Phương thức này cũng nhận thêm hai đối số,
    >>> 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
    
    5 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
    
    6. 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
    
    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. Bạn cần chuyển các giá trị phù hợp cho các đối số này trong lệnh gọi tới
    >>> 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, như bạn sẽ học trong giây lát

  • Dòng 9 in 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)
    
    2 chạy bước khởi tạo đối tượng

  • Dòng 10 và 11 lần lượt khởi tạo

    >>> 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. Để 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
    
    5 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
    
    6

  • Dòng 13 và 14 triển khai phương thức đặc biệt, cung cấp cách biểu diễn chuỗi thích 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)
    
    6 của bạn

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)
6 tại chỗ, bạn có thể khám phá cách hoạt động của quy trình khởi tạo trong thực tế. Lưu mã của bạn vào tệp có tên
>>> class Rectangle:
..     def __init__(self, width, height):
..         self.width = width
..         self.height = height
...

>>> rectangle = Rectangle(21, 42)
>>> rectangle.width
21
>>> rectangle.height
42
8 và trong cửa sổ dòng lệnh. Sau đó chạy đoạn 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 hàm tạo của 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
9 tạo, khởi tạo và trả về một thể hiện mới của lớp. Thể hiện 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'
0

Trong ví dụ này, lệnh gọi hàm tạo cũng cho bạn biết các bước mà Python chạy bên trong để 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)
3 và sau đó 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)
2, dẫn đến một phiên bản mới và được khởi tạo đầy đủ của
>>> 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)
6, như bạn đã xác nhận ở cuối ví dụ

Để tiếp tục tìm hiểu về khởi tạo 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)

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)
3 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)
6 của mình, chuyển chính lớp đó làm đố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 sẽ bỏ qua lệnh gọi tớ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)
2

Ghi chú. Đoạn mã trên nhằm mục đích là một ví dụ minh họa về cách quy trình khởi tạo hoạt động bên trong. Đó không phải là điều mà bạn thường làm trong mã thực

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)
2 với một bộ đố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)
6 của bạn được khởi tạo đúng cách, với tất cả các thuộc tính của nó được thiết lập

Một chi tiết tinh tế và quan trọng cần lưu ý 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)
3 là nó cũng có thể trả về một thể hiện của một lớp khác với lớp thực hiện chính phương thức đó. Khi điều đó xảy ra, Python không 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)
2 trong lớp hiện tại, bởi vì không có cách nào để biết rõ ràng cách khởi tạo một đối tượng của một lớp khác

Xem xét ví dụ sau, trong đó 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)
3 của lớp
>>> 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
2 trả về một thể hiện của lớp
>>> 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
3

# 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

Bởi vì

>>> 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
4 trả về một thể hiện của một lớp khác, Python không 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
5. Để xác nhận hành vi này, hãy lưu mã vào một tệp có tên là
>>> 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
6 rồi chạy mã sau trong phiên Python tương tác

>>>

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

Cuộc gọi đến phương thức khởi tạo lớp

>>> 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
7 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
4, trả về một thể hiện của
>>> 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
3 thay vì
>>> 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
2. Đó là lý do tại sao
>>> 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
5 không bao giờ chạy. Lưu ý rằng
>>> class Person:
..     def __init__(self, name, birth_date):
..         self.name = name
..         self.birth_date = birth_date
...

>>> class Employee(Person):
..     def __init__(self, name, birth_date, position):
..         super().__init__(name, birth_date)
..         self.position = position
...

>>> john = Employee("John Doe", "2001-02-07", "Python Developer")

>>> john.name
'John Doe'
>>> john.birth_date
'2001-02-07'
>>> john.position
'Python Developer'
2 không có thuộc tính
>>> class Person:
..     def __init__(self, name, birth_date):
..         self.name = name
..         self.birth_date = birth_date
...

>>> class Employee(Person):
..     def __init__(self, name, birth_date, position):
..         super().__init__(name, birth_date)
..         self.position = position
...

>>> john = Employee("John Doe", "2001-02-07", "Python Developer")

>>> john.name
'John Doe'
>>> john.birth_date
'2001-02-07'
>>> john.position
'Python Developer'
3. Ngược lại,
>>> class Person:
..     def __init__(self, name, birth_date):
..         self.name = name
..         self.birth_date = birth_date
...

>>> class Employee(Person):
..     def __init__(self, name, birth_date, position):
..         super().__init__(name, birth_date)
..         self.position = position
...

>>> john = Employee("John Doe", "2001-02-07", "Python Developer")

>>> john.name
'John Doe'
>>> john.birth_date
'2001-02-07'
>>> john.position
'Python Developer'
2 có thuộc tính
>>> class Person:
..     def __init__(self, name, birth_date):
..         self.name = name
..         self.birth_date = birth_date
...

>>> class Employee(Person):
..     def __init__(self, name, birth_date, position):
..         super().__init__(name, birth_date)
..         self.position = position
...

>>> john = Employee("John Doe", "2001-02-07", "Python Developer")

>>> john.name
'John Doe'
>>> john.birth_date
'2001-02-07'
>>> john.position
'Python Developer'
5 với giá trị là
>>> class Person:
..     def __init__(self, name, birth_date):
..         self.name = name
..         self.birth_date = birth_date
...

>>> class Employee(Person):
..     def __init__(self, name, birth_date, position):
..         super().__init__(name, birth_date)
..         self.position = position
...

>>> john = Employee("John Doe", "2001-02-07", "Python Developer")

>>> john.name
'John Doe'
>>> john.birth_date
'2001-02-07'
>>> john.position
'Python Developer'
6

Bây giờ bạn đã biết các bước mà Python thực hiện trong nội bộ để tạo các thể hiện của một lớp nhất định, bạn đã sẵn sàng tìm hiểu sâu hơn một chút về các đặc điểm khác 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)
2,
>>> 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)
3 và các bước mà chúng chạy

Loại bỏ các quảng cáo

Khởi 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) 2

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)
2 có lẽ là phương thức đặc biệt phổ biến nhất mà bạn từng 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)
2. Ghi đè phương thức này sẽ cho phép bạn khởi tạo đúng các đối tượng của mình

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 lập tức trong mã của mình. Trong phần này, bạn sẽ học những điều cơ bản để 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)
2 của riêng mình 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 Trình khởi tạo đối tượng tùy chỉnh

Việc triển khai đơn giả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)
2 mà bạn có thể viết sẽ chỉ đảm nhiệm việc gán các đối số đầu vào cho các thuộc tính đối tượng phù hợp. Ví dụ: giả sử bạn đang 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})"
04 yêu cầu các 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})"
05 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})"
06. 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 đã học 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)
2 chạy bước thứ hai của quy 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.__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)
3, giữ thể hiện mới là kết quả của 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)
3. 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)
2 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 các đối số
 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})"
05 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})"
06 của hình chữ nhật bằng cách sử dụng các đối số
 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})"
13 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})"
14 thà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)
2

Điều quan trọng cần lưu ý là, không tính

>>> 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)
3, các đối số 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)
2 chính là những đối số mà bạn đã chuyển trong lệnh gọi hàm tạo của 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)
2 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)
2 không được khác vớ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})"
20, nếu không bạn sẽ nhận được một ngoại lệ

>>>

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

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)
2 cố gắng trả về một số nguyên, kết quả là đưa ra một ngoạ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})"
21 trong thời gian chạy

Thông báo lỗi trong ví dụ trên cho biết 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)
2 sẽ 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})"
20. Tuy nhiên, bạn không cần 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})"
20 một cách rõ ràng, bởi vì các phương thức và hàm không có câu lệ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})"
27 rõ ràng chỉ 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})"
20 một cách ngầm định trong Python

Với cách 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)
2 ở trên, bạn đảm bảo rằ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})"
05 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})"
06 được khởi tạo ở trạng thái hợp lệ khi bạn gọi phương thức khởi tạo của lớp với các đối số thích hợp. Bằng cách đó, các hình chữ nhật của bạn sẽ sẵn sàng để sử dụng ngay sau khi quá trình xây dựng kết thúc

Trong

>>> 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, bạn cũng có thể chạy bất kỳ phép biến đổi nào đối với các đối số đầu vào để khởi tạo đúng các thuộc tính thể hiện. Ví dụ: nếu người dùng của bạn sẽ sử dụng trực tiế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})"
04, thì bạn có thể muốn xác thực
 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})"
13 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})"
14 được cung cấp và đảm bảo rằng chúng chính xác trước khi khởi tạo các thuộc tính tương ứng

>>>_______ 58 _______

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

Trong triển khai cập nhật này 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)
2, bạn đảm bảo rằng các đối số đầu và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})"
13 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})"
14 là số dương trước khi khởi tạo các 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})"
05 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})"
06 tương ứng. Nếu một trong hai xác thực không thành công, thì bạn sẽ nhận được mộ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})"
41

Ghi chú. Một kỹ thuật Pythonic hơn để giải quyết xác thực thuộc tính là biến thuộc tính thành thuộc tính. Để tìm hiểu thêm về các thuộc tính, hãy xem thuộc tính của Python(). Thêm thuộc tính được quản lý vào lớp học của bạn

Bây giờ, giả sử rằng bạn đang sử dụng tính kế thừa để tạo phân cấp lớp tùy chỉnh và sử dụng lại một số chức năng trong mã của bạn. Nếu các lớp con của bạn 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)
2, thì phương thức này phải gọi rõ ràng 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)
2 của lớp cơ sở với các đối số thích hợp để đảm bảo khởi tạo đúng các thể hiện. Để làm điều này, bạn nê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
1 tích hợp như trong ví dụ sau

>>>

>>> class Person:
..     def __init__(self, name, birth_date):
..         self.name = name
..         self.birth_date = birth_date
...

>>> class Employee(Person):
..     def __init__(self, name, birth_date, position):
..         super().__init__(name, birth_date)
..         self.position = position
...

>>> john = Employee("John Doe", "2001-02-07", "Python Developer")

>>> john.name
'John Doe'
>>> john.birth_date
'2001-02-07'
>>> john.position
'Python Developer'

Dòng đầu tiên trong 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)
2 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})"
46 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})"
47 với các đối số 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})"
48 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})"
49. Cuộc gọi này đảm bảo việc khởi tạo 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})"
50 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})"
51 trong lớp cha,
 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})"
52. Kỹ thuật này cho phép bạn đến lớp cơ sở với các thuộc tính và chức năng mới

Để kết thúc phần này, bạn nên biết rằng việc triển khai cơ sở 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)
2 đến 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
0 tích hợp sẵn. Việc triển khai này được gọi tự động khi bạn không cung cấ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)
2 rõ ràng trong các lớp học của mình

Loại bỏ các quảng cáo

Xây dựng Trình khởi tạo đối tượng linh hoạt

Bạn có thể làm cho bước khởi tạo đối tượng của mình trở nên linh hoạt và linh hoạt bằng cách điều chỉ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)
2. Cuối cùng, một trong những kỹ thuật phổ biến nhất là sử dụng các đối số tùy chọn. Kỹ thuật này cho phép bạn viết các lớp trong đó hàm tạo chấp nhận các bộ đối số đầu vào khác nhau tại thời điểm khởi tạo. Việc sử dụng đối số nào tại một thời điểm nhất định sẽ phụ thuộc vào nhu cầu và ngữ cảnh cụ thể của bạn

Ví dụ nhanh, hãy xem 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})"
57 sau đâ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})"
0

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)
2 lấy một đối số thông thường có tên 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})"
48. Nó cũng nhận một tên 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})"
60, mặc đị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})"
61. 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})"
60 có một 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 giá trị 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

 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})"
60. Nếu đối số này 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})"
61, thì bạn sẽ nhận được lời chào thân mật khi gọi 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})"
65. Nếu không, bạn sẽ nhận được một lời chào trang trọng hơn

Để dùng 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})"
57, hãy tiếp tục và lưu mã vào tệ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})"
67. 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 đoạn 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})"
1

Trong ví dụ đầu tiên, bạn tạo 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})"
68 bằng cách chuyển một giá trị cho đối số
 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})"
48 và dựa vào giá trị mặc định 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})"
60. Bạn nhận được một lời chào thân mật trên màn hình khi 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})"
65 trên đố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})"
68

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

 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})"
48 và đối số
 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})"
60 để 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})"
57. 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})"
60 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})"
77, kết quả của việc 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})"
65 là một lời chào trang trọng

Mặc dù đây là một ví dụ về đồ chơi, nhưng nó cho thấy các giá trị đối số mặc định là một tính năng Python mạnh mẽ như thế nào mà bạn có thể sử dụng để viết các trình 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ách sử dụng các bộ đối số khác nhau tùy thuộc vào nhu cầu của bạn

Đồng ý. Bây giờ bạn đã biết những kiến ​​thức cơ bản 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)
2 và bước khởi tạo đối tượng, đã đến lúc chuyển hướng và bắt đầu tìm hiểu sâu hơn 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)
3 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) 3

Khi viết các lớp Python, thông thường bạn không cần cung cấp triển khai phương thức đặ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)
3 của riêng mình. 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
0 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)
3 để tạo các lớp con của các loại, chẳng hạn 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})"
87 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})"
88

Trong các phần sau, bạn sẽ học cách viết 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)
3 trong các lớp học của mình. Để làm điều này, bạn sẽ viết mã một số ví dụ để biết khi nào bạn có thể cần ghi đè phương thức này

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

Thông thường, bạn sẽ viết 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)
3 chỉ khi bạn cần kiểm soát việc tạo phiên bản mới ở mức thấp. Bây giờ, nếu bạn cần triển khai tùy chỉnh phương pháp này, thì bạn nên làm theo một số 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})"
    
    91 với các đối số thích hợp
  2. Tùy chỉnh phiên bản mới theo nhu cầu cụ thể của bạn
  3. Trả lại phiên bản mới để tiếp tục quá trình khởi tạo

Với ba bước ngắn gọn này, bạn sẽ có thể tùy chỉnh bước tạo phiên bản trong quy trình khởi tạo Python. Đây là một ví dụ về cách bạn có thể dịch các bước này sang mã Python

 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

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)
3. 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)
3 lấy lớp hiện tại làm đối số thường được 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
2

Lưu ý rằng bạn đang 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 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
5 để làm cho phương thức linh hoạt hơn và dễ bảo 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 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)
3 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 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
5, trừ khi bạn có lý do chính đáng để theo một mẫu 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)
3, bạn gọ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)
3 của lớp cha để tạo một thể hiện mới và cấp phát bộ nhớ cho nó. Để truy cậ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)
3 của lớp cha, 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
1. Chuỗi cuộc gọi này đưa bạn đế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)
04, đâ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)
3 cho tất cả các lớp Python

Ghi chú. 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
0 tích hợp là lớp cơ sở mặc định của tất cả các lớp Python

Bước tiếp theo là tùy chỉnh phiên bản mới 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 phiên bản hiện có. Cuối cùng, ở bước thứ ba, bạn cần trả về phiên bả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à bản thâ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)
04 chỉ chấp nhận một đối số duy nhất, lớp để khởi tạo. Nếu 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)
04 với nhiều đối số hơn, thì bạn nhận được
 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})"
21

>>>

 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

Trong ví dụ này, bạn bàn giao

# 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 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
5 làm đối số bổ sung trong cuộc gọi tớ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})"
91. Cơ 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)
04 chỉ chấp nhận lớp làm đối số, vì vậy bạn nhận được mộ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})"
21 khi bạn khởi tạo lớp

Tuy nhiê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)
04 vẫn chấp nhận và chuyển các đối số bổ sung 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)
2 nếu lớp của 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)
3, như trong biến thể sau 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

>>>

 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

Trong quá trình 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 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)
3. Việc tạo đối tượng sau đó được ủy quyề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)
04, hiện đang chấp nhậ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)
22 và chuyển 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)
23 để hoàn tất quá trình khởi tạo. Bây giờ bạn có thể tạo các thể hiện mới và được khởi tạo đầy đủ 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, giống 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)
25 trong ví dụ

Mát mẻ. Bây giờ bạn đã biết những kiến ​​thức cơ bản để viết triển khai của riêng mình 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)
3, bạn đã sẵn sàng đi sâu vào 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

Loại bỏ các quảng cáo

Phân lớp các loại tích hợp không thể thay đổi

Để bắt đầu, bạn sẽ bắt đầu với trường hợp sử dụng 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)
3 bao gồm phân lớp con một loại tích hợp sẵn không thể thay đổi. Ví dụ, giả sử bạn cần viết một 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)
28 dưới dạng một lớp con của loạ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})"
86 của Python. Lớp học của bạn sẽ có một thuộc tính bổ sung để lưu trữ đơn vị dùng để đo khoảng cách

Đây là 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)
2

>>>

 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

Khi bạn phân lớp một kiểu dữ liệu tích hợp sẵn không thể thay đổi, 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à đã quá muộn để thay đổi giá trị đó trong quá trình khởi tạo. Ngoài ra,

>>> 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)
31 được gọi dưới mui xe và nó không xử lý các đối số bổ sung theo cách giống 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)
04. Đây là những gì làm tăng lỗi trong ví dụ của bạn

Để khắc phục sự cố này, bạn có thể khởi tạo đối tượng tại thời điểm tạo bằ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)
3 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)
2. Đây là cách bạn có thể làm điều này trong thực 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})"
6

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)
3 chạy ba bước mà bạn đã học trong phần trước. Đầu tiên, phương thức tạo 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
2, 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})"
91. Lần này, cuộc gọi quay trở lạ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)
31, tạo ra một phiên bản mới và khởi tạo nó bằng cách sử dụng _________22 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
>>> 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)
40 vào nó. Cuối cùng, phiên bản mới được trả lại

Ghi chú. 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)
28 trong ví dụ trên không cung cấp cơ chế chuyển đổi đơn vị phù hợp. Điều này có nghĩa là một cái gì đó 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)
42 sẽ không cố gắng chuyển đổi đơn vị trước khi thêm các giá trị. Nếu bạn quan tâm đến việc chuyển đổi đơn vị, hãy xem dự án Pint trên PyPI

Đó là nó. Bây giờ 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)
28 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ữ đơn vị mà bạn đang đo khoảng cách. Không giống như giá trị dấu phẩy động được lưu trữ trong một phiên bản nhất đị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)
28, 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)
40 có thể thay đổi, vì vậy bạn có thể thay đổi giá trị của nó bất kỳ lúc nào bạn muốn. Cuối cùng, lưu ý cách gọi hàm cho thấy rằng lớp của bạn kế thừa các tính năng và phương thức 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})"
86

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

Trả lại một đối tượng của một lớp khác là một yêu cầu có thể làm tăng nhu cầu 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)
3. Tuy nhiên bạn nên cẩn thận vì trong trường hợp này Python bỏ qua hoàn toàn bước khởi tạo. Vì vậy, bạn sẽ có trách nhiệm đưa đối tượng mới tạo về trạng thái hợp lệ trước khi sử dụng nó trong mã của mình

Hãy xem ví dụ sau, trong đó 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)
49 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)
3 để trả về các thể hiện của các lớp được chọn ngẫu nhiê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})"
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)
49 cung cấ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)
3 để tạo 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ó

Đây là cách bạn có thể sử dụ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)
49 này như một xưởng sản xuất đồ vật nuô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})"
8

Mỗi khi bạn khởi tạ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)
49, 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ế đố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)
3 có thể trả về. Việc 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)
3 theo cách như vậy sẽ biến một lớp thành một nhà máy sản xuất các đối tượng linh hoạt và mạnh mẽ, không giới hạn ở các thể hiện của chính nó

Cuối cùng, hãy lưu ý rằ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)
2 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)
49 không bao giờ chạy. Đó là bởi 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)
59 luôn trả về các đối tượng của một lớp khác chứ không phải của 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)
49

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

Đôi khi bạn cần triển khai một lớp chỉ 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 đơn. Trong tình huống 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)
3 rất hữu ích vì nó có thể giúp bạn hạn chế số lượng phiên bản mà một lớp nhất định có thể có

Ghi chú. Hầu hết các nhà phát triển Python có kinh nghiệm sẽ lập luận rằng bạn không cần triển khai mẫu thiết kế đơn lẻ trong Python trừ khi bạn đã có một lớp làm việc và cần thêm chức năng của mẫu lên trên nó

Thời gian còn lại, bạn có thể sử dụng hằng số cấp mô-đun để có cùng chức năng đơn lẻ mà không cần phải viết một lớp tương đối phức tạp

Đây là một ví dụ về mã hóa 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)
62 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)
3 cho phép tạo chỉ một phiên bản 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)
3 kiểm tra sự tồn tại của các phiên bản trước đó được lưu trong bộ đệm 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})"
9

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)
62 trong ví dụ này có tên 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)
66 mặc đị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})"
20 và hoạt động như một bộ đệm. 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)
3 kiểm tra xem có tồn tại phiên bản trước đó hay không bằng cách kiểm tra điều kiệ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)
69

Ghi chú. Trong ví dụ trê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)
62 không cung cấp triển khai 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)
2. Nếu bạn cần một lớp như thế này 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)
2, thì hãy nhớ rằng phương thức này sẽ chạy mỗi khi bạn gọi hàm tạ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)
73. Hành vi này có thể gây ra các lỗi và hiệu ứng khởi tạo kỳ lạ

Nếu điều kiện này là đúng, thì khối 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)
74 sẽ tạo một phiên bả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)
62 và lưu trữ 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)
76. Cuối cùng, phương thức trả về phiên bản mới hoặc phiên bản hiện có cho người gọi

Sau đó, bạn khởi tạ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)
62 hai lần để cố gắng xây dựng hai đối tượng khác nhau,
>>> 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)
78 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)
79. Nếu bạn so sánh danh tính của các đối tượng này với toán 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)
80, thì bạn sẽ lưu ý rằng cả hai đối tượng đều là cùng một đối tượng. Các tê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)
78 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)
79 chỉ giữ các tham chiếu đến cùng một đố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)
62

Loại bỏ các quảng cáo

Mô phỏng một phầ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) 84

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)
3 trong mã của bạn, bạn có thể nâng cao kỹ năng Python của mình và viết một hàm xuất xưởng mô phỏng một phầ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)
86. 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)
87 cho phép bạn tạo các lớp con 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})"
87 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 bộ dữ liệu

Đoạn mã dưới đây triển khai 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)
89 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)
3 của một lớp lồng nhau có tên 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)
91

>>> 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)
0

Đây là cách chức năng xuất xưởng này hoạt động theo từng dòng

  • Dòng 3 nhậ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)
    
    92 từ mô-đun. Hàm này cho phép bạn truy xuất các mục bằng cách sử dụng chỉ mục của chúng trong chuỗi chứa

  • Dòng 5 định nghĩ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)
    
    89. Hàm này nhận đối số đầu tiên có tên 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)
    
    95, đối số này sẽ chứa tên của lớp con bộ 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)
    
    96 cho phép bạn chuyển số lượng tên trường không xác định dưới dạng chuỗi

  • Dòng 6 định nghĩa một biến cục bộ để chứa số trường được đặt tên do người dùng cung cấp

  • Dòng 8 định nghĩa một lớp lồng nhau có tên 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)
    
    91, kế thừa 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})"
    
    87 tích hợp

  • Dòng 9 cung cấp một thuộc tính lớp. Thuộc tính này xác định một tuple để giữ các thuộc tính thể hiện. Bộ dữ liệu này tiết kiệm bộ nhớ bằng cách đóng vai trò thay thế cho từ điển của cá thể, nếu không sẽ đóng vai trò tương tự

  • Dòng 11 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)
    
    3 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
    
    2 là đối số đầu tiên của nó. Việc triển khai này cũng sử dụng đố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
    
    4 để chấp nhận số lượng giá trị trường không xác định

  • 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 cần lưu trữ trong bộ dữ liệu cuối cùng có khác với số lượng trường được đặt tên hay không. Nếu trường hợp đó xảy ra, thì điều kiện sẽ 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})"
    
    21 kèm theo thông báo lỗi

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

    >>> 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)
    
    05 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)
    
    95

  • Dòng 18 và 19 xác định một vòng 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)
    
    07 biến mọi trường được đặt tên thành một thuộc tí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)
    
    92 để trả về mục tại mục tiêu
    >>> 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)
    
    09. Vòng lặp sử dụng chức năng 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.__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)
    
    11 tích hợp sẵn cung cấp giá trị
    >>> 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)
    
    09 thích hợp

  • 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})"
    
    91 như bình thường

  • Dòng 22 và 23 định nghĩa một phương thức

    >>> class Rectangle:
    ..     def __init__(self, width, height):
    ..         self.width = width
    ..         self.height = height
    ...
    
    >>> rectangle = Rectangle(21, 42)
    >>> rectangle.width
    21
    >>> rectangle.height
    42
    
    5 cho lớp con tuple của bạn

  • Dòng 25 trả về 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)
    
    91 mới được tạo

Để dùng thử

>>> 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)
89 của bạn, hãy kích hoạt một phiên tương tác trong thư mục chứa tệ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)
17 và chạy đoạn 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)
1

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)
6 mới 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)
89. Đối số đầu tiên trong cuộc gọi này đại diện cho tên mà đối tượng lớp kết quả sẽ sử dụng. Đố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)
6 bằng cách gọi hàm tạo của lớp với các giá trị thích 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
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. Để 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ỉ mục để truy xuất các giá trị vì lớp của bạn là một lớp con của bộ

Vì bộ dữ liệu là kiểu dữ liệu bất biến trong Python, nên bạn không thể gán giá trị mới cho tọa độ của điểm tại chỗ. Nếu bạn cố gắng làm điều đó, thì bạn sẽ nhận được mộ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)
23

Cuối cùng, 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)
46 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'
0 của bạn làm đố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

Phần kết luận

Bây giờ bạn đã biết cách các hàm tạo của lớp Python cho phép bạn khởi tạo các lớp, vì vậy 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 hàm tạo của lớp kích hoạt bên trong quá trình khởi tạo hoặc xây dựng, trải qua quá trình tạo cá thể và khởi tạo cá thể. Các bước này được thúc đẩy 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)
3 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)
2

Bằng cách tìm hiểu về các hàm tạo lớp của Python, quy 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)
3 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)
2, giờ đây bạn có thể quản lý cách các lớp tùy chỉnh của mình xây dựng các thể hiện mới

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

  • Cách quy trình khởi tạo của Python hoạt động nội bộ
  • Cách các 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)
    
    2 của riêng bạn giúp bạn tùy chỉnh khởi tạo đối tượ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)
    
    3 cho phép tạo đối tượng tùy chỉnh

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

Tiền thưởng miễn phí. Nhấp vào đây để có quyền truy cập vào Bảng cheat Python OOP miễn phí chỉ cho bạn các hướng dẫn, video và sách hay nhất để tìm hiểu thêm về Lập trình hướng đối tượng với Python

Đánh dấu là đã hoàn thành

Xem ngay Hướng dẫn này có một khóa học video liên quan do nhóm Real Python tạo. Xem nó cùng với hướng dẫn bằng văn bản để hiểu sâu hơn. Sử dụng Trình tạo lớp Python

🐍 Thủ thuật Python 💌

Nhận một Thủ thuật Python ngắn và hấp dẫn được gửi đến hộp thư đến của bạn vài ngày một lần. Không có thư rác bao giờ. Hủy đăng ký bất cứ lúc nào. Được quản lý bởi nhóm Real Python

Đối tượng trong đối số lớp Python là gì?

Gửi cho tôi thủ thuật Python »

Giới thiệu về Leodanis Pozo Ramos

Đối tượng trong đối số lớp Python là gì?
Đối tượng trong đối số lớp Python là gì?

Leodanis là một kỹ sư công nghiệp yêu thích Python và phát triển phần mềm. Anh ấy là một nhà phát triển Python tự học với hơn 6 năm kinh nghiệm. Anh ấy là một nhà văn đam mê kỹ thuật với số lượng bài báo được xuất bản ngày càng tăng trên Real Python và các trang web khác

» Tìm hiểu thêm về Leodanis


Mỗi hướng dẫn tại Real Python được tạo bởi một nhóm các nhà phát triển để nó đáp ứng các tiêu chuẩn chất lượng cao của chúng tôi. Các thành viên trong nhóm đã làm việc trong hướng dẫn này là

Đối tượng trong đối số lớp Python là gì?

Aldren

Đối tượng trong đối số lớp Python là gì?

Bartosz

Đối tượng trong đối số lớp Python là gì?

Geir Arne

Đối tượng trong đối số lớp Python là gì?

kate

Đối tượng trong đối số lớp Python là gì?

Sadie

Bậc thầy Kỹ năng Python trong thế giới thực Với quyền truy cập không giới hạn vào Python thực

Tham gia với chúng tôi và có quyền truy cập vào hàng nghìn hướng dẫn, khóa học video thực hành và cộng đồng các Pythonistas chuyên gia

Nâng cao kỹ năng Python của bạn »

Chuyên gia Kỹ năng Python trong thế giới thực
Với quyền truy cập không giới hạn vào Python thực

Tham gia với chúng tôi và có quyền truy cập vào hàng ngàn hướng dẫn, khóa học video thực hành và cộng đồng Pythonistas chuyên gia

Nâng cao kỹ năng Python của bạn »

Bạn nghĩ sao?

Đánh giá bài viết này

Tweet Chia sẻ Chia sẻ Email

Bài học số 1 hoặc điều yêu thích mà bạn đã học được là gì?

Mẹo bình luận. Những nhận xét hữu ích nhất là những nhận xét được viết với mục đích học hỏi hoặc giúp đỡ các sinh viên khác. và nhận câu trả lời cho các câu hỏi phổ biến trong cổng thông tin hỗ trợ của chúng tôi

Đối số đối tượng trong Python là gì?

Đối tượng là thể hiện của lớp trong python có trường và phương thức i. e. , giá trị và hàm liên quan . Python cho phép các lập trình viên của nó truyền đối tượng vào phương thức. Và cũng trả về các đối tượng từ một phương thức. Đây là một chương trình để minh họa điều này, Chương trình truyền các đối tượng làm đối số và trả về các đối tượng từ hàm.

Đối tượng trong lớp có nghĩa là Python là gì?

Đối tượng là bất cứ thứ gì bạn muốn thao tác hoặc thay đổi trong khi làm việc với mã . Mỗi khi một đối tượng lớp được khởi tạo, đó là khi chúng ta khai báo một biến, một đối tượng mới sẽ được khởi tạo từ đầu.

Đối tượng () có nghĩa là gì trong Python?

Hàm đối tượng Python() . the base for all classes, it holds the built-in properties and methods which are default for all classes.

Các đối tượng trong các lớp học là gì?

Một đối tượng là một thành viên hoặc một "thực thể" của một lớp . Một đối tượng có trạng thái trong đó tất cả các thuộc tính của nó có các giá trị mà bạn xác định rõ ràng hoặc được xác định theo cài đặt mặc định.