Hướng dẫn python class optional arguments - đối số tùy chọn lớp python
You can set default parameters: Show
If you don't explicitly call the class with from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update9 and def greeting(name: str) -> str: return 'Hello ' + name00, your instance will use the defaults you defined in the init parameters. So when you create an instance of this object, you can use all four parameters as normal: def greeting(name: str) -> str: return 'Hello ' + name01 Or you can omit the parameters with defaults with def greeting(name: str) -> str: return 'Hello ' + name02, which would be interpreted as def greeting(name: str) -> str: return 'Hello ' + name03 You can use some default values but not all of them as well, by referencing the name of the parameter: def greeting(name: str) -> str: return 'Hello ' + name04 uses from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update9's default but not def greeting(name: str) -> str: return 'Hello ' + name00's. Python won't allow you to do def greeting(name: str) -> str: return 'Hello ' + name07 as a default parameter ( def greeting(name: str) -> str: return 'Hello ' + name08 isn't an existing object that the class definition can see), so the def greeting(name: str) -> str: return 'Hello ' + name09 line handles this with an def greeting(name: str) -> str: return 'Hello ' + name10 statement that in effect does the same thing. Mới trong phiên bản 3.5. Nội phân Chính showShow
Mã nguồn: lib/gõ.py Lib/typing.py Ghi chú Nếu from typing import NewType UserId = NewType('UserId', int) # Fails at runtime and does not typecheck class AdminUserId(UserId): pass95 được sử dụng, các chú thích không được đánh giá theo thời gian định nghĩa chức năng. Thay vào đó, chúng được lưu trữ dưới dạng chuỗi trong from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)80. Điều này làm cho việc sử dụng các trích dẫn xung quanh chú thích không cần thiết (xem PEP 563). Mới trong phiên bản 3.5.2.PEP 484. For a simplified introduction to type hints, see PEP 483. Mới trong phiên bản 3.5. def greeting(name: str) -> str: return 'Hello ' + name Nội phân Chính show Peps¶ có liên quan Peps¶ có liên quanGõ bí danhPEP 484 and PEP 483, a number of PEPs have modified and enhanced Python’s framework for type annotations. These include:
Gõ bí danhCác loại chung do người dùng xác định Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4]) Bất kỳ loại from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ... Danh nghĩa so với phân nhóm cấu trúc Nội dung mô -đunĐặc biệt gõ nguyên thủy from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313) Bộ sưu tập bê tông chung chung def get_user_name(user_id: UserId) -> str: ... # typechecks user_a = get_user_name(UserId(42351)) # does not typecheck; an int is not a UserId user_b = get_user_name(-1) Lớp học cơ sở trừu tượng Jo # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341) Giao thức Chức năng và Người trang trí Người trợ giúp nội tâm from typing import NewType UserId = NewType('UserId', int) # Fails at runtime and does not typecheck class AdminUserId(UserId): pass Mã nguồn: lib/gõ.py from typing import NewType UserId = NewType('UserId', int) ProUserId = NewType('ProUserId', UserId) Thời gian chạy Python không thực thi chức năng và chú thích loại biến. Chúng có thể được sử dụng bởi các công cụ của bên thứ ba như trình kiểm tra loại, IDE, linter, v.v. Xem PEP 484 để biết thêm chi tiết.PEP 484 for more details. Ghi chú Hãy nhớ lại rằng việc sử dụng một bí danh loại tuyên bố hai loại tương đương với nhau. Thực hiện def greeting(name: str) -> str: return 'Hello ' + name56 sẽ làm cho trình kiểm tra loại tĩnh điều trị def greeting(name: str) -> str: return 'Hello ' + name57 là chính xác tương đương với def greeting(name: str) -> str: return 'Hello ' + name58 trong mọi trường hợp. Điều này rất hữu ích khi bạn muốn đơn giản hóa chữ ký loại phức tạp. Ngược lại, def greeting(name: str) -> str: return 'Hello ' + name41 tuyên bố một loại là một loại phụ của loại khác. Thực hiện def greeting(name: str) -> str: return 'Hello ' + name60 sẽ làm cho trình kiểm tra loại tĩnh xử lý def greeting(name: str) -> str: return 'Hello ' + name49 dưới dạng lớp con của def greeting(name: str) -> str: return 'Hello ' + name58, có nghĩa là giá trị của loại def greeting(name: str) -> str: return 'Hello ' + name58 không thể được sử dụng ở những nơi dự kiến giá trị của loại def greeting(name: str) -> str: return 'Hello ' + name49. Điều này rất hữu ích khi bạn muốn ngăn chặn các lỗi logic với chi phí thời gian chạy tối thiểu. Mới trong phiên bản 3.5.2. Đã thay đổi trong phiên bản 3.10: def greeting(name: str) -> str: return 'Hello ' + name41 is now a class rather than a function. There is some additional runtime cost when calling def greeting(name: str) -> str: return 'Hello ' + name41 over a regular function. However, this cost will be reduced in 3.11.0. Gọi là có thể gọi đượcCác khung mong đợi các chức năng gọi lại của chữ ký cụ thể có thể được loại gợi ý bằng cách sử dụng def greeting(name: str) -> str: return 'Hello ' + name67. Ví dụ: from collections.abc import Callable def feeder(get_next_item: Callable[[], str]) -> None: # Body def async_query(on_success: Callable[[int], None], on_error: Callable[[int, Exception], None]) -> None: # Body async def on_update(value: str) -> None: # Body callback: Callable[[str], Awaitable[None]] = on_update Có thể khai báo loại trả về của một cuộc gọi có thể gọi mà không chỉ định chữ ký cuộc gọi bằng cách thay thế một dấu chấm lửng theo nghĩa đen cho danh sách các đối số trong loại gợi ý: def greeting(name: str) -> str: return 'Hello ' + name68. Các thiết bị gọi lấy các thiết bị gọi khác làm đối số có thể chỉ ra rằng các loại tham số của chúng phụ thuộc vào nhau bằng cách sử dụng def greeting(name: str) -> str: return 'Hello ' + name33. Ngoài ra, nếu có thể gọi được thêm hoặc xóa các đối số khỏi các loại gọi khác, toán tử def greeting(name: str) -> str: return 'Hello ' + name34 có thể được sử dụng. Họ lần lượt nhận dạng def greeting(name: str) -> str: return 'Hello ' + name71 và def greeting(name: str) -> str: return 'Hello ' + name72. Thuốc generics;Vì thông tin loại về các đối tượng được giữ trong các container không thể được suy ra tĩnh một cách chung, nên các lớp cơ sở trừu tượng đã được mở rộng để hỗ trợ đăng ký để biểu thị các loại dự kiến cho các yếu tố container. def greeting(name: str) -> str: return 'Hello ' + name0 Generics có thể được tham số hóa bằng cách sử dụng một nhà máy có sẵn trong việc gõ gọi là def greeting(name: str) -> str: return 'Hello ' + name14. def greeting(name: str) -> str: return 'Hello ' + name1 Các loại chung do người dùng xác địnhMột lớp do người dùng xác định có thể được định nghĩa là một lớp chung. def greeting(name: str) -> str: return 'Hello ' + name2 def greeting(name: str) -> str: return 'Hello ' + name74 Là một lớp cơ sở định nghĩa rằng lớp def greeting(name: str) -> str: return 'Hello ' + name75 lấy một tham số loại duy nhất def greeting(name: str) -> str: return 'Hello ' + name76. Điều này cũng làm cho def greeting(name: str) -> str: return 'Hello ' + name76 có giá trị như một loại trong cơ thể lớp. Lớp cơ sở def greeting(name: str) -> str: return 'Hello ' + name15 xác định def greeting(name: str) -> str: return 'Hello ' + name79 để def greeting(name: str) -> str: return 'Hello ' + name80 hợp lệ dưới dạng loại: def greeting(name: str) -> str: return 'Hello ' + name3 Một loại chung có thể có bất kỳ số lượng biến loại. Tất cả các loại của def greeting(name: str) -> str: return 'Hello ' + name14 đều được cho phép làm tham số cho một loại chung: def greeting(name: str) -> str: return 'Hello ' + name4 Mỗi đối số biến loại thành def greeting(name: str) -> str: return 'Hello ' + name15 phải khác biệt. Điều này không hợp lệ: def greeting(name: str) -> str: return 'Hello ' + name5 Bạn có thể sử dụng nhiều kế thừa với def greeting(name: str) -> str: return 'Hello ' + name15: def greeting(name: str) -> str: return 'Hello ' + name6 Khi kế thừa từ các lớp chung, một số biến loại có thể được sửa: def greeting(name: str) -> str: return 'Hello ' + name7 Trong trường hợp này def greeting(name: str) -> str: return 'Hello ' + name84 có một tham số duy nhất, def greeting(name: str) -> str: return 'Hello ' + name76. Sử dụng một lớp chung mà không chỉ định các tham số loại giả định def greeting(name: str) -> str: return 'Hello ' + name11 cho mỗi vị trí. Trong ví dụ sau, def greeting(name: str) -> str: return 'Hello ' + name87 không chung chung mà là kế thừa ngầm từ def greeting(name: str) -> str: return 'Hello ' + name88: def greeting(name: str) -> str: return 'Hello ' + name8 Bí danh loại chung được xác định của người dùng cũng được hỗ trợ. Ví dụ: def greeting(name: str) -> str: return 'Hello ' + name9 Đã thay đổi trong phiên bản 3.7: def greeting(name: str) -> str: return 'Hello ' + name15 no longer has a custom metaclass. Generics do người dùng xác định cho các biểu thức tham số cũng được hỗ trợ thông qua các biến đặc tả tham số ở dạng def greeting(name: str) -> str: return 'Hello ' + name90. Hành vi phù hợp với các biến loại, được mô tả ở trên là các biến đặc tả tham số được coi bởi mô -đun gõ là một biến loại chuyên dụng. Một ngoại lệ cho điều này là một danh sách các loại có thể được sử dụng để thay thế một def greeting(name: str) -> str: return 'Hello ' + name33: Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])0 Hơn nữa, một chung chỉ có một biến đặc tả tham số sẽ chấp nhận danh sách tham số trong các biểu mẫu def greeting(name: str) -> str: return 'Hello ' + name92 và cả def greeting(name: str) -> str: return 'Hello ' + name93 vì lý do thẩm mỹ. Trong nội bộ, cái sau được chuyển đổi thành cái trước, vì vậy những điều sau đây là tương đương: Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])1 Xin lưu ý rằng các chất generic với def greeting(name: str) -> str: return 'Hello ' + name33 có thể không đúng def greeting(name: str) -> str: return 'Hello ' + name95 sau khi thay thế trong một số trường hợp vì chúng được dự định chủ yếu để kiểm tra loại tĩnh. Đã thay đổi trong phiên bản 3.10: def greeting(name: str) -> str: return 'Hello ' + name15 can now be parameterized over parameter expressions. See def greeting(name: str) -> str: return 'Hello ' + name33 and PEP 612 for more details. Một lớp chung do người dùng xác định có thể có ABC như các lớp cơ sở mà không có xung đột metaclass. Các metaclass chung không được hỗ trợ. Kết quả của việc chung hóa tham số hóa được lưu trữ và hầu hết các loại trong mô -đun gõ đều có thể băm và có thể so sánh cho sự bình đẳng. Bất kỳ loạiMột loại đặc biệt là def greeting(name: str) -> str: return 'Hello ' + name11. Một trình kiểm tra loại tĩnh sẽ coi mọi loại là tương thích với def greeting(name: str) -> str: return 'Hello ' + name11 và def greeting(name: str) -> str: return 'Hello ' + name11 là tương thích với mọi loại. Điều này có nghĩa là có thể thực hiện bất kỳ hoạt động hoặc phương thức gọi trên giá trị của loại def greeting(name: str) -> str: return 'Hello ' + name11 và gán nó cho bất kỳ biến nào: Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])2 Lưu ý rằng không có typechking nào được thực hiện khi gán giá trị loại def greeting(name: str) -> str: return 'Hello ' + name11 cho một loại chính xác hơn. Ví dụ: Trình kiểm tra loại tĩnh đã không báo cáo lỗi khi gán Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])03 cho Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])04 mặc dù Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])04 đã được tuyên bố là loại def greeting(name: str) -> str: return 'Hello ' + name18 và nhận được giá trị def greeting(name: str) -> str: return 'Hello ' + name42 khi chạy! Hơn nữa, tất cả các chức năng mà không có loại trả về hoặc loại tham số sẽ mặc định sử dụng def greeting(name: str) -> str: return 'Hello ' + name11: Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])3 Hành vi này cho phép def greeting(name: str) -> str: return 'Hello ' + name11 được sử dụng như một hatch thoát ra khi bạn cần trộn mã được gõ linh hoạt và thống kê. Tương phản hành vi của def greeting(name: str) -> str: return 'Hello ' + name11 với hành vi của Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])11. Tương tự như def greeting(name: str) -> str: return 'Hello ' + name11, mọi loại là một loại phụ của Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])11. Tuy nhiên, không giống như def greeting(name: str) -> str: return 'Hello ' + name11, điều ngược lại không đúng: Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])11 không phải là một kiểu con của mọi loại khác. Điều đó có nghĩa là khi loại giá trị là Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])11, trình kiểm tra loại sẽ từ chối hầu hết tất cả các hoạt động trên đó và gán nó cho một biến (hoặc sử dụng nó làm giá trị trả về) của một loại chuyên dụng hơn là lỗi loại. Ví dụ: Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])4 Sử dụng Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])11 để chỉ ra rằng một giá trị có thể là bất kỳ loại nào theo cách kiểu an toàn. Sử dụng def greeting(name: str) -> str: return 'Hello ' + name11 để chỉ ra rằng một giá trị được gõ động. Danh nghĩa so với phân nhóm cấu trúcBan đầu PEP 484 xác định hệ thống loại tĩnh Python là sử dụng tiểu mục danh nghĩa. Điều này có nghĩa là một lớp Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])19 được cho phép trong đó một lớp Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])20 được mong đợi nếu và chỉ khi Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])19 là một lớp con của Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])20.PEP 484 defined the Python static type system as using nominal subtyping. This means that a class Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])19 is allowed where a class Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])20 is expected if and only if Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])19 is a subclass of Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])20. Yêu cầu này trước đây cũng áp dụng cho các lớp cơ sở trừu tượng, chẳng hạn như Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])23. Vấn đề với phương pháp này là một lớp phải được đánh dấu rõ ràng để hỗ trợ họ, điều này không có âm thanh và không giống như những gì người ta thường làm trong mã python được gõ động một cách tự động. Ví dụ, điều này phù hợp với PEP 484:PEP 484: Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])5 PEP 544 cho phép giải quyết vấn đề này bằng cách cho phép người dùng viết mã trên mà không có các lớp cơ sở rõ ràng trong định nghĩa lớp, cho phép Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])24 to be implicitly considered a subtype of both Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])25 and Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])26 by static type checkers. This is known as structural subtyping (or static duck-typing): Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])6 Hơn nữa, bằng cách phân lớp một lớp đặc biệt def greeting(name: str) -> str: return 'Hello ' + name22, người dùng có thể xác định các giao thức tùy chỉnh mới để thưởng thức hoàn toàn phân nhóm cấu trúc (xem các ví dụ bên dưới). Nội dung mô -đunCác mô -đun xác định các lớp, chức năng và trang trí sau đây. Ghi chú Mô-đun này xác định một số loại là các lớp con của các lớp thư viện tiêu chuẩn có sẵn cũng mở rộng def greeting(name: str) -> str: return 'Hello ' + name15 để hỗ trợ các biến loại bên trong Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])29. Các loại này trở nên dư thừa trong Python 3.9 khi các lớp có sẵn tương ứng được tăng cường để hỗ trợ Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])29. Các loại dự phòng không được chấp nhận kể từ Python 3.9 nhưng không có cảnh báo phản đối nào sẽ được đưa ra bởi thông dịch viên. Dự kiến các trình kiểm tra loại sẽ gắn cờ các loại không dùng nữa khi chương trình được kiểm tra nhắm mục tiêu Python 3.9 hoặc mới hơn. Các loại không dùng sẽ được xóa khỏi mô -đun def greeting(name: str) -> str: return 'Hello ' + name20 trong phiên bản Python đầu tiên được phát hành 5 năm sau khi phát hành Python 3.9.0. Xem chi tiết trong PEP 585, Generics Generics trong các bộ sưu tập tiêu chuẩn.PEP 585—Type Hinting Generics In Standard Collections. Đặc biệt gõ nguyên thủyCác loại đặc biệtChúng có thể được sử dụng dưới dạng các loại trong các chú thích và không hỗ trợ Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])29. ________ 233 ________ 234¶ Loại đặc biệt chỉ ra một loại không bị ràng buộc.
Loại đặc biệt chỉ ra rằng một hàm không bao giờ trả về. Ví dụ: Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])7 Mới trong phiên bản 3.5.4. Mới trong phiên bản 3.6.2. Chú thích đặc biệt để tuyên bố rõ ràng một bí danh. Ví dụ:type alias. For example: Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])8 Xem PEP 613 để biết thêm chi tiết về các bí danh loại rõ ràng.PEP 613 for more details about explicit type aliases. Mới trong phiên bản 3.10. Mẫu đặc biệtChúng có thể được sử dụng làm loại trong các chú thích bằng cách sử dụng Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])29, mỗi loại có một cú pháp duy nhất. ________ 233 ________ 243¶ Loại tuple; Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])44 là loại tuple của hai mục với mục đầu tiên của loại X và loại thứ hai của loại Y. Loại tuple trống có thể được viết là Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])45. Ví dụ: Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])46 là một bộ của hai yếu tố tương ứng với các biến loại T1 và T2. Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])47 là một bộ dữ liệu của int, float và một chuỗi. Để chỉ định một tuple có độ dài thay đổi của loại đồng nhất, hãy sử dụng Ellipsis theo nghĩa đen, ví dụ: Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])48. Một đơn vị Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])49 tương đương với Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])50, và lần lượt Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])51. ________ 233 ________ 253¶ Loại công đoàn; Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])54 tương đương với def greeting(name: str) -> str: return 'Hello ' + name30 và có nghĩa là X hoặc Y. Để xác định một liên minh, hãy sử dụng, ví dụ: Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])56 hoặc tốc ký Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])57. Sử dụng tốc ký đó được khuyến khích. Thông tin chi tiết:
Đã thay đổi trong phiên bản 3.7: Don Tiết loại bỏ các lớp con rõ ràng khỏi các công đoàn khi chạy.Don’t remove explicit subclasses from unions at runtime. ________ 233 ________ 261¶Loại tùy chọn. Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])62 tương đương với Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])63 (hoặc Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])64). Lưu ý rằng đây không phải là khái niệm giống như một đối số tùy chọn, đó là một đối số có mặc định. Một đối số tùy chọn với mặc định không yêu cầu vòng loại Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])65 về chú thích loại của nó chỉ vì nó là tùy chọn. Ví dụ: from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...3 Mặt khác, nếu giá trị rõ ràng của def greeting(name: str) -> str: return 'Hello ' + name39 được phép, việc sử dụng Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])65 là phù hợp, cho dù đối số có phải là tùy chọn hay không. Ví dụ: from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...4 Đã thay đổi trong phiên bản 3.10: Tùy chọn hiện có thể được viết là Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])63. See union type expressions. ________ 233 ________ 270¶ Loại có thể gọi được; Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])71 là một hàm của (int) -> str. Cú pháp đăng ký phải luôn được sử dụng với chính xác hai giá trị: danh sách đối số và loại trả về. Danh sách đối số phải là danh sách các loại hoặc dấu chấm lửng; Loại trả về phải là một loại duy nhất. Không có cú pháp để chỉ ra các đối số từ khóa hoặc tùy chọn; Các loại chức năng như vậy hiếm khi được sử dụng làm loại gọi lại. def greeting(name: str) -> str: return 'Hello ' + name68 (Ellipsis theo nghĩa đen) có thể được sử dụng để gõ Gợi ý có thể gọi được lấy bất kỳ số lượng đối số nào và trả lại Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])73. Một đơn giản def greeting(name: str) -> str: return 'Hello ' + name13 tương đương với Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])75, và lần lượt Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])76. Các thiết bị gọi lấy các thiết bị gọi khác làm đối số có thể chỉ ra rằng các loại tham số của chúng phụ thuộc vào nhau bằng cách sử dụng def greeting(name: str) -> str: return 'Hello ' + name33. Ngoài ra, nếu có thể gọi được thêm hoặc xóa các đối số khỏi các loại gọi khác, toán tử def greeting(name: str) -> str: return 'Hello ' + name34 có thể được sử dụng. Họ lần lượt nhận dạng def greeting(name: str) -> str: return 'Hello ' + name71 và def greeting(name: str) -> str: return 'Hello ' + name72. ________ 233 ________ 282¶ Được sử dụng với def greeting(name: str) -> str: return 'Hello ' + name13 và def greeting(name: str) -> str: return 'Hello ' + name33 để nhập chú thích một thứ tự cao hơn có thể gọi có thể thêm, xóa hoặc biến đổi các tham số của một người khác có thể gọi được. Việc sử dụng ở dạng Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])85. def greeting(name: str) -> str: return 'Hello ' + name34 hiện chỉ hợp lệ khi được sử dụng làm đối số đầu tiên cho def greeting(name: str) -> str: return 'Hello ' + name13. Tham số cuối cùng của def greeting(name: str) -> str: return 'Hello ' + name34 phải là def greeting(name: str) -> str: return 'Hello ' + name33. Ví dụ, để chú thích một người trang trí Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])90 cung cấp một Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])91 cho chức năng được trang trí, def greeting(name: str) -> str: return 'Hello ' + name34 có thể được sử dụng để chỉ ra rằng Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])90 mong đợi một cuộc gọi có thể gọi được trong một Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])94 là đối số đầu tiên và trả về một dấu hiệu có thể gọi với một loại khác nhau. Trong trường hợp này, def greeting(name: str) -> str: return 'Hello ' + name33 chỉ ra rằng các loại tham số có thể gọi được trả về phụ thuộc vào các loại tham số của có thể gọi được được truyền vào: from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...5 Mới trong phiên bản 3.10. Xem thêm
Một biến được chú thích bằng from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...02 có thể chấp nhận giá trị loại from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...02. Ngược lại, một biến được chú thích với from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...04 có thể chấp nhận các giá trị là bản thân các lớp - cụ thể, nó sẽ chấp nhận đối tượng lớp của from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...02. Ví dụ: from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...6 Lưu ý rằng from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...04 là Covariant: from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...7 Thực tế là from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...04 là hiệp phương sai ngụ ý rằng tất cả các lớp con của from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...02 nên thực hiện cùng một chữ ký của hàm tạo và chữ ký phương pháp lớp là from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...02. Trình kiểm tra loại nên gắn cờ vi phạm này, nhưng cũng nên cho phép các cuộc gọi xây dựng trong các lớp con phù hợp với các cuộc gọi xây dựng trong lớp cơ sở được chỉ định. Làm thế nào trình kiểm tra loại được yêu cầu để xử lý trường hợp cụ thể này có thể thay đổi trong các sửa đổi trong tương lai của PEP 484.PEP 484. Các tham số pháp lý duy nhất cho from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...10 là các lớp, def greeting(name: str) -> str: return 'Hello ' + name11, các biến loại và liên minh của bất kỳ loại nào trong số này. Ví dụ:type variables, and unions of any of these types. For example: from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...8 from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...12 tương đương với from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...10, lần lượt tương đương với from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...14, là gốc của hệ thống phân cấp Metaclass Python. Mới trong phiên bản 3.5.2. ________ 233 ________ 316¶Một loại có thể được sử dụng để chỉ ra các trình kiểm tra loại rằng biến hoặc tham số chức năng tương ứng có giá trị tương đương với nghĩa đen được cung cấp (hoặc một trong một số nghĩa đen). Ví dụ: from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...9 from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...17 không thể được phân nhóm. Trong thời gian chạy, một giá trị tùy ý được cho phép là đối số loại thành from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...17, nhưng người kiểm tra loại có thể áp đặt các hạn chế. Xem PEP 586 để biết thêm chi tiết về các loại nghĩa đen.PEP 586 for more details about literal types. Mới trong phiên bản 3.8. Đã thay đổi trong phiên bản 3.9.1: def greeting(name: str) -> str: return 'Hello ' + name25 now de-duplicates parameters. Equality comparisons of def greeting(name: str) -> str: return 'Hello ' + name25 objects are no longer order dependent. def greeting(name: str) -> str: return 'Hello ' + name25 objects will now raise a from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...22 exception during equality comparisons if one of their parameters are not hashable.________ 233 ________ 324¶ Loại cấu trúc đặc biệt để đánh dấu các biến lớp. Như được giới thiệu trong PEP 526, một chú thích thay đổi được bọc trong classvar chỉ ra rằng một thuộc tính nhất định được dự định sẽ được sử dụng làm biến lớp và không nên được đặt trên các trường hợp của lớp đó. Cách sử dụng:PEP 526, a variable annotation wrapped in ClassVar indicates that a given attribute is intended to be used as a class variable and should not be set on instances of that class. Usage: from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)0 def greeting(name: str) -> str: return 'Hello ' + name21 chỉ chấp nhận các loại và không thể được đăng ký thêm. def greeting(name: str) -> str: return 'Hello ' + name21 không phải là một lớp và không nên được sử dụng với from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...27 hoặc from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...28. def greeting(name: str) -> str: return 'Hello ' + name21 không thay đổi hành vi thời gian chạy Python, nhưng nó có thể được sử dụng bởi các trình kiểm tra loại bên thứ ba. Ví dụ: Trình kiểm tra loại có thể gắn cờ mã sau là lỗi: from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)1 Mới trong phiên bản 3.5.3. ________ 233 ________ 331¶Một cấu trúc gõ đặc biệt để chỉ ra để nhập trình kiểm tra rằng một tên không thể được gán lại hoặc ghi đè trong một lớp con. Ví dụ: from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)2 Không có kiểm tra thời gian chạy của các thuộc tính này. Xem PEP 591 để biết thêm chi tiết.PEP 591 for more details. Mới trong phiên bản 3.8. ________ 233 ________ 333¶Một loại, được giới thiệu trong PEP 593 ( from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...34), để trang trí các loại hiện có với siêu dữ liệu cụ thể theo ngữ cảnh (có thể là nhiều phần của nó, vì def greeting(name: str) -> str: return 'Hello ' + name29 là variadic). Cụ thể, loại def greeting(name: str) -> str: return 'Hello ' + name76 có thể được chú thích bằng siêu dữ liệu from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...37 thông qua TypeHint from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...38. Siêu dữ liệu này có thể được sử dụng để phân tích tĩnh hoặc trong thời gian chạy. Nếu một thư viện (hoặc công cụ) gặp phải một kiểu chữ from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...38 và không có logic đặc biệt cho siêu dữ liệu from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...37, nó sẽ bỏ qua nó và chỉ coi loại này là def greeting(name: str) -> str: return 'Hello ' + name76. Không giống như chức năng from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...42 hiện đang tồn tại trong mô -đun def greeting(name: str) -> str: return 'Hello ' + name20, vô hiệu hóa hoàn toàn các chú thích đánh máy trên một hàm hoặc một lớp, loại ____129 cho phép cả hai lần kiểm tra typic của def greeting(name: str) -> str: return 'Hello ' + name76 (có thể bỏ qua một cách an toàn from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...37) .PEP 593 ( from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...34), to decorate existing types with context-specific metadata (possibly multiple pieces of it, as def greeting(name: str) -> str: return 'Hello ' + name29 is variadic). Specifically, a type def greeting(name: str) -> str: return 'Hello ' + name76 can be annotated with metadata from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...37 via the typehint from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...38. This metadata can be used for either static analysis or at runtime. If a library (or tool) encounters a typehint from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...38 and has no special logic for metadata from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...37, it should ignore it and simply treat the type as def greeting(name: str) -> str: return 'Hello ' + name76. Unlike the from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...42 functionality that currently exists in the def greeting(name: str) -> str: return 'Hello ' + name20 module which completely disables typechecking annotations on a function or a class, the def greeting(name: str) -> str: return 'Hello ' + name29 type allows for both static typechecking of def greeting(name: str) -> str: return 'Hello ' + name76 (which can safely ignore from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...37) together with runtime access to from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...37 within a specific application. Cuối cùng, trách nhiệm của cách diễn giải các chú thích (nếu có) là trách nhiệm của công cụ hoặc thư viện gặp phải loại def greeting(name: str) -> str: return 'Hello ' + name29. Một công cụ hoặc thư viện gặp phải loại def greeting(name: str) -> str: return 'Hello ' + name29 có thể quét qua các chú thích để xác định xem chúng có được quan tâm không (ví dụ: sử dụng from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...27). Khi một công cụ hoặc thư viện không hỗ trợ chú thích hoặc gặp một chú thích không xác định, nó chỉ nên bỏ qua nó và coi loại chú thích là loại cơ bản. Nó tùy thuộc vào công cụ tiêu thụ các chú thích để quyết định xem khách hàng có được phép có nhiều chú thích trên một loại hay không và làm thế nào để hợp nhất các chú thích đó. Vì loại def greeting(name: str) -> str: return 'Hello ' + name29 cho phép bạn đặt một số chú thích của cùng loại (hoặc khác nhau) trên bất kỳ nút nào, nên các công cụ hoặc thư viện tiêu thụ các chú thích đó chịu trách nhiệm đối phó với các bản sao tiềm năng. Ví dụ: nếu bạn đang thực hiện phân tích phạm vi giá trị, bạn có thể cho phép điều này: from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)3 Chuyển from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...52 đến from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...53 cho phép người ta truy cập vào các chú thích bổ sung khi chạy. Các chi tiết của cú pháp:
Mới trong phiên bản 3.9. ________ 233 ________ 361¶Biểu mẫu gõ đặc biệt được sử dụng để chú thích loại trả về của chức năng bảo vệ loại do người dùng xác định. def greeting(name: str) -> str: return 'Hello ' + name36 chỉ chấp nhận một đối số loại duy nhất. Trong thời gian chạy, các chức năng được đánh dấu theo cách này sẽ trả về Boolean. def greeting(name: str) -> str: return 'Hello ' + name36 nhằm mục đích thu hẹp loại lợi ích - Một kỹ thuật được sử dụng bởi các trình kiểm tra loại tĩnh để xác định một loại biểu thức chính xác hơn trong luồng mã chương trình. Thông thường thu hẹp loại được thực hiện bằng cách phân tích luồng mã có điều kiện và áp dụng việc thu hẹp vào một khối mã. Biểu thức có điều kiện ở đây đôi khi được gọi là một người bảo vệ kiểu người khác: from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)9 Đôi khi sẽ thuận tiện khi sử dụng chức năng Boolean do người dùng định nghĩa làm người bảo vệ loại. Một chức năng như vậy nên sử dụng from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...64 làm loại trả về của nó để cảnh báo các trình kiểm tra loại tĩnh cho ý định này. Sử dụng from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...65 nói với trình kiểm tra loại tĩnh rằng đối với một hàm đã cho:
Ví dụ: def get_user_name(user_id: UserId) -> str: ... # typechecks user_a = get_user_name(UserId(42351)) # does not typecheck; an int is not a UserId user_b = get_user_name(-1)0 Nếu from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...68 là phương thức lớp hoặc phiên bản, thì loại trong def greeting(name: str) -> str: return 'Hello ' + name36 bản đồ theo loại tham số thứ hai sau from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...70 hoặc from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...71. Nói tóm lại, Mẫu from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...72, có nghĩa là nếu from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...73 trả về from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...66, thì from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...75 thu hẹp từ from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...76 đến from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...77. Ghi chú from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...77 không cần phải là một dạng hẹp hơn của from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...76 - nó thậm chí có thể là một hình thức rộng hơn. Lý do chính là để cho phép những thứ như thu hẹp from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...80 đến from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...81 mặc dù sau này không phải là một loại phụ của cái trước, vì from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...82 là bất biến. Trách nhiệm của việc viết bộ bảo vệ loại an toàn loại được để lại cho người dùng. def greeting(name: str) -> str: return 'Hello ' + name36 cũng hoạt động với các biến loại. Để biết thêm thông tin, hãy xem PEP 647 (Bộ bảo vệ loại do người dùng xác định).PEP 647 (User-Defined Type Guards). Mới trong phiên bản 3.10. Xây dựng các loại chung chungChúng không được sử dụng trong các chú thích. Họ đang xây dựng các khối để tạo ra các loại chung. Lớp ________ 233 ________ 385¶Lớp cơ sở trừu tượng cho các loại chung. Một loại chung thường được khai báo bằng cách kế thừa từ một khởi tạo của lớp này với một hoặc nhiều biến loại. Ví dụ: loại ánh xạ chung có thể được định nghĩa là: def get_user_name(user_id: UserId) -> str: ... # typechecks user_a = get_user_name(UserId(42351)) # does not typecheck; an int is not a UserId user_b = get_user_name(-1)1 Lớp này sau đó có thể được sử dụng như sau: def get_user_name(user_id: UserId) -> str: ... # typechecks user_a = get_user_name(UserId(42351)) # does not typecheck; an int is not a UserId user_b = get_user_name(-1)2 Lớp ________ 233 ________ 387¶ Loại biến. Usage: def get_user_name(user_id: UserId) -> str: ... # typechecks user_a = get_user_name(UserId(42351)) # does not typecheck; an int is not a UserId user_b = get_user_name(-1)3 Loại biến tồn tại chủ yếu vì lợi ích của người kiểm tra loại tĩnh. Chúng phục vụ như các tham số cho các loại chung cũng như các định nghĩa chức năng chung. Xem def greeting(name: str) -> str: return 'Hello ' + name15 để biết thêm thông tin về các loại chung. Chức năng chung hoạt động như sau: def get_user_name(user_id: UserId) -> str: ... # typechecks user_a = get_user_name(UserId(42351)) # does not typecheck; an int is not a UserId user_b = get_user_name(-1)4 Lưu ý rằng các biến loại có thể bị ràng buộc, bị ràng buộc hoặc không, nhưng không thể bị ràng buộc và bị ràng buộc. Các biến loại bị ràng buộc và các biến loại ràng buộc có ngữ nghĩa khác nhau theo một số cách quan trọng. Sử dụng một biến loại bị ràng buộc có nghĩa là def greeting(name: str) -> str: return 'Hello ' + name14 chỉ có thể được giải quyết là chính xác là một trong những ràng buộc được đưa ra: def get_user_name(user_id: UserId) -> str: ... # typechecks user_a = get_user_name(UserId(42351)) # does not typecheck; an int is not a UserId user_b = get_user_name(-1)5 Tuy nhiên, sử dụng một biến loại ràng buộc có nghĩa là def greeting(name: str) -> str: return 'Hello ' + name14 sẽ được giải quyết bằng cách sử dụng loại cụ thể nhất có thể: def get_user_name(user_id: UserId) -> str: ... # typechecks user_a = get_user_name(UserId(42351)) # does not typecheck; an int is not a UserId user_b = get_user_name(-1)6 Các biến loại có thể được liên kết với các loại cụ thể, các loại trừu tượng (ABC hoặc giao thức) và thậm chí cả các công đoàn của các loại: def get_user_name(user_id: UserId) -> str: ... # typechecks user_a = get_user_name(UserId(42351)) # does not typecheck; an int is not a UserId user_b = get_user_name(-1)7 Các biến loại ràng buộc đặc biệt hữu ích để chú thích from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...91 đóng vai trò là hàm tạo thay thế. Trong ví dụ sau (bởi Raymond Hettinger), biến loại from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...02 được liên kết với lớp from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...93 thông qua việc sử dụng tham chiếu chuyển tiếp. Sử dụng biến loại này để chú thích lớp from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...94, thay vì mã hóa loại trả về loại trả về from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...93, có nghĩa là trình kiểm tra loại có thể suy ra chính xác loại trả về ngay cả khi phương thức được gọi trên lớp con: def get_user_name(user_id: UserId) -> str: ... # typechecks user_a = get_user_name(UserId(42351)) # does not typecheck; an int is not a UserId user_b = get_user_name(-1)8 Trong thời gian chạy, from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...96 sẽ tăng from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...22. Nói chung, from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...27 và from collections.abc import Sequence ConnectionOptions = dict[str, str] Address = tuple[str, int] Server = tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: Sequence[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None: ...28 không nên được sử dụng với các loại. Các biến loại có thể được đánh dấu hiệp phương sai hoặc contravariant bằng cách vượt qua from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)00 hoặc from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)01. Xem PEP 484 để biết thêm chi tiết. Theo mặc định, các biến loại là bất biến.PEP 484 for more details. By default, type variables are invariant. Lớp ________ 233 ________ 403 (tên, *, ràng buộc = none, covariant = false(name, *, bound=None, covariant=False, contravariant=False)¶ Biến đặc tả tham số. Một phiên bản chuyên dụng của from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)04. Usage: Các biến đặc tả tham số tồn tại chủ yếu vì lợi ích của bộ kiểm tra loại tĩnh. Chúng được sử dụng để chuyển tiếp các loại tham số của một người có thể gọi cho một người khác có thể gọi - một mẫu thường được tìm thấy trong các chức năng và bộ trang trí bậc cao. Chúng chỉ hợp lệ khi được sử dụng trong def greeting(name: str) -> str: return 'Hello ' + name34 hoặc là đối số đầu tiên cho def greeting(name: str) -> str: return 'Hello ' + name13 hoặc làm tham số cho thuốc generic do người dùng xác định. Xem def greeting(name: str) -> str: return 'Hello ' + name15 để biết thêm thông tin về các loại chung. Ví dụ: để thêm ghi nhật ký cơ bản vào một hàm, người ta có thể tạo Trình trang trí from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)08 để ghi nhật ký các cuộc gọi chức năng. Biến đặc tả tham số cho biết trình kiểm tra loại rằng có thể gọi được chuyển vào trình trang trí và phần gọi mới được trả về bởi nó có các tham số loại phụ thuộc giữa các tham số: def get_user_name(user_id: UserId) -> str: ... # typechecks user_a = get_user_name(UserId(42351)) # does not typecheck; an int is not a UserId user_b = get_user_name(-1)9 Không có def greeting(name: str) -> str: return 'Hello ' + name33, cách đơn giản nhất để chú thích điều này trước đây là sử dụng def greeting(name: str) -> str: return 'Hello ' + name14 với ràng buộc Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector. new_vector = scale(2.0, [1.0, -4.2, 5.4])75. Tuy nhiên, điều này gây ra hai vấn đề:
Vì def greeting(name: str) -> str: return 'Hello ' + name33 nắm bắt cả các tham số vị trí và từ khóa, from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)23 và from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)24 có thể được sử dụng để chia def greeting(name: str) -> str: return 'Hello ' + name33 thành các thành phần của nó. from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)23 đại diện cho bộ dữ liệu của các tham số vị trí trong một cuộc gọi nhất định và chỉ nên được sử dụng để chú thích from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)13. from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)24 thể hiện ánh xạ các tham số từ khóa đến các giá trị của chúng trong một cuộc gọi nhất định và chỉ nên được sử dụng để chú thích from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)14. Cả hai thuộc tính đều yêu cầu tham số chú thích phải nằm trong phạm vi. Trong thời gian chạy, from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)23 và from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)24 tương ứng là các trường hợp của from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)32 và from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)33. Các biến đặc tả tham số được tạo bằng from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)00 hoặc from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)01 có thể được sử dụng để khai báo các loại chung hiệp phương sai hoặc contravariant. Đối số from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)36 cũng được chấp nhận, tương tự như def greeting(name: str) -> str: return 'Hello ' + name14. Tuy nhiên, ngữ nghĩa thực tế của các từ khóa này vẫn chưa được quyết định. Mới trong phiên bản 3.10. Ghi chú Chỉ các biến đặc tả tham số được xác định trong phạm vi toàn cầu mới có thể được ngâm. Xem thêm
Đối số và từ khóa Các thuộc tính của A def greeting(name: str) -> str: return 'Hello ' + name33. Thuộc tính from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)23 của def greeting(name: str) -> str: return 'Hello ' + name33 là một ví dụ là from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)32 và from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)24 là một ví dụ của from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)33. Chúng được dự định để hướng nội thời gian chạy và không có ý nghĩa đặc biệt đối với người kiểm tra loại tĩnh. Gọi from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)52 trên một trong hai đối tượng này sẽ trả về bản gốc def greeting(name: str) -> str: return 'Hello ' + name33: # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)0 Mới trong phiên bản 3.10. Ghi chúChỉ các biến đặc tả tham số được xác định trong phạm vi toàn cầu mới có thể được ngâm. Xem thêm PEP 612 - Các biến đặc tả tham số (PEP đã giới thiệudef greeting(name: str) -> str: return 'Hello ' + name33 và def greeting(name: str) -> str: return 'Hello ' + name34).(Generic)¶ def greeting(name: str) -> str: return 'Hello ' + name13 và def greeting(name: str) -> str: return 'Hello ' + name34. # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)2 ________ 233 ________ 443¶ ________ 233 ________ 445¶ # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)3 Đối số và từ khóa Các thuộc tính của A def greeting(name: str) -> str: return 'Hello ' + name33. Thuộc tính from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)23 của def greeting(name: str) -> str: return 'Hello ' + name33 là một ví dụ là from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)32 và from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)24 là một ví dụ của from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)33. Chúng được dự định để hướng nội thời gian chạy và không có ý nghĩa đặc biệt đối với người kiểm tra loại tĩnh.PEP 544 for details. Protocol classes decorated with from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)61 (described later) act as simple-minded runtime protocols that check only the presence of given attributes, ignoring their type signatures. Gọi from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)52 trên một trong hai đối tượng này sẽ trả về bản gốc def greeting(name: str) -> str: return 'Hello ' + name33: # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)4 ________ 233 ________ 455¶ from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)56 là from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)57 được định nghĩa là from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313)58. Nó có nghĩa là được sử dụng cho các chức năng có thể chấp nhận bất kỳ loại chuỗi nào mà không cho phép các loại chuỗi khác nhau trộn. Ví dụ: # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)1 Lớp ________ 233 ________ 460 (chung) ¶ # 'output' is of type 'int', not 'UserId' output = UserId(23413) + UserId(54341)5 Ghi chú Lớp cơ sở cho các lớp giao thức. Các lớp giao thức được xác định như thế này: ________ 233 ________ 455¶
|