Gõ tuple trong Python là gì?
danh sách list_int. Danh sách[int] = [3] danh sách list_string. Danh sách[str] = [“edcoffee”] set set_int. Set[int] = {9,1,3} tuple (số phần tử hữu hạn) tuple_float. Tuple[float, str, int] = (3. 5, “giáo dục”, 9) tuple (số phần tử vô hạn) tuple_float. Tuple[float, …] = (3. 5, 2. 3, 45. 6) lệnh dict_kv. Dict[str, int] = {“chìa khóa”. 4}
PEP 484, cung cấp thông số kỹ thuật về giao diện của một hệ thống kiểu trong Python3, đã giới thiệu khái niệm về gợi ý kiểu. Hơn nữa, để hiểu rõ hơn về triết lý thiết kế gợi ý kiểu, điều quan trọng là phải đọc PEP 483, điều này sẽ hữu ích để hỗ trợ một pythoneer hiểu lý do tại sao Python giới thiệu một hệ thống kiểu. Mục tiêu chính của bảng gian lận này là hiển thị một số cách sử dụng phổ biến về gợi ý loại trong Python3 Show
Mục lục Không kiểm tra loạidef fib(n): a, b = 0, 1 for _ in range(n): yield a b, a = a + b, b print([n for n in fib(3.6)]) đầu ra # errors will not be detected until runtime $ python fib.py Traceback (most recent call last): File "fib.py", line 8, in Với loại kiểm tra# give a type hint from typing import Generator def fib(n: int) -> Generator: a: int = 0 b: int = 1 for _ in range(n): yield a b, a = a + b, b print([n for n in fib(3.6)]) đầu ra # errors will be detected before running $ mypy --strict fib.py fib.py:12: error: Argument 1 to "fib" has incompatible type "float"; expected "int" các loại cơ bảnimport io import re from collections import deque, namedtuple from typing import ( Dict, List, Tuple, Set, Deque, NamedTuple, IO, Pattern, Match, Text, Optional, Sequence, Iterable, Mapping, MutableMapping, Any, ) # without initializing x: int # any type y: Any y = 1 y = "1" # built-in var_int: int = 1 var_str: str = "Hello Typing" var_byte: bytes = b"Hello Typing" var_bool: bool = True var_float: float = 1. var_unicode: Text = u'\u2713' # could be none var_could_be_none: Optional[int] = None var_could_be_none = 1 # collections var_set: Set[int] = {i for i in range(3)} var_dict: Dict[str, str] = {"foo": "Foo"} var_list: List[int] = [i for i in range(3)] var_static_length_Tuple: Tuple[int, int, int] = (1, 2, 3) var_dynamic_length_Tuple: Tuple[int, ...] = (i for i in range(10, 3)) var_deque: Deque = deque([1, 2, 3]) var_nametuple: NamedTuple = namedtuple('P', ['x', 'y']) # io var_io_str: IO[str] = io.StringIO("Hello String") var_io_byte: IO[bytes] = io.BytesIO(b"Hello Bytes") var_io_file_str: IO[str] = open(__file__) var_io_file_byte: IO[bytes] = open(__file__, 'rb') # re p: Pattern = re.compile("(https?)://([^/\r\n]+)(/[^\r\n]*)?") m: Optional[Match] = p.match("https://www.python.org/") # duck types: list-like var_seq_list: Sequence[int] = [1, 2, 3] var_seq_tuple: Sequence[int] = (1, 2, 3) var_iter_list: Iterable[int] = [1, 2, 3] var_iter_tuple: Iterable[int] = (1, 2, 3) # duck types: dict-like var_map_dict: Mapping[str, str] = {"foo": "Foo"} var_mutable_dict: MutableMapping[str, str] = {"bar": "Bar"} Chức năngfrom typing import Generator, Callable # function def gcd(a: int, b: int) -> int: while b: a, b = b, a % b return a # callback def fun(cb: Callable[[int, int], int]) -> int: return cb(55, 66) # lambda f: Callable[[int], int] = lambda x: x * 2 Các lớp họcfrom typing import ClassVar, Dict, List class Foo: x: int = 1 # instance variable. default = 1 y: ClassVar[str] = "class var" # class variable def __init__(self) -> None: self.i: List[int] = [0] def foo(self, a: int, b: str) -> Dict[int, str]: return {a: b} foo = Foo() foo.x = 123 print(foo.x) print(foo.i) print(Foo.y) print(foo.foo(1, "abc")) Máy phát điệnfrom typing import Generator # Generator[YieldType, SendType, ReturnType] def fib(n: int) -> Generator[int, None, None]: a: int = 0 b: int = 1 while n > 0: yield a b, a = a + b, b n -= 1 g: Generator = fib(10) i: Iterator[int] = (x for x in range(3)) Máy phát điện không đồng bộ________số 8_______ Trình quản lý bối cảnhfrom typing import ContextManager, Generator, IO from contextlib import contextmanager @contextmanager def open_file(name: str) -> Generator: f = open(name) yield f f.close() cm: ContextManager[IO] = open_file(__file__) with cm as f: print(f.read()) Trình quản lý bối cảnh không đồng bộ# errors will not be detected until runtime $ python fib.py Traceback (most recent call last): File "fib.py", line 8, in0 Tránh truy cập from typing import ClassVar, Dict, List class Foo: x: int = 1 # instance variable. default = 1 y: ClassVar[str] = "class var" # class variable def __init__(self) -> None: self.i: List[int] = [0] def foo(self, a: int, b: str) -> Dict[int, str]: return {a: b} foo = Foo() foo.x = 123 print(foo.x) print(foo.i) print(Foo.y) print(foo.foo(1, "abc")) 2# errors will not be detected until runtime $ python fib.py Traceback (most recent call last): File "fib.py", line 8, in1 đầu ra # errors will not be detected until runtime $ python fib.py Traceback (most recent call last): File "fib.py", line 8, in2 Đối số chỉ vị trí# errors will not be detected until runtime $ python fib.py Traceback (most recent call last): File "fib.py", line 8, in3 đầu ra # errors will not be detected until runtime $ python fib.py Traceback (most recent call last): File "fib.py", line 8, in4 Nhiều giá trị trả về# errors will not be detected until runtime $ python fib.py Traceback (most recent call last): File "fib.py", line 8, in5 Liên minh [Bất kỳ, Không] == Tùy chọn [Bất kỳ]# errors will not be detected until runtime $ python fib.py Traceback (most recent call last): File "fib.py", line 8, in6 Hãy cẩn thận với from typing import ClassVar, Dict, List class Foo: x: int = 1 # instance variable. default = 1 y: ClassVar[str] = "class var" # class variable def __init__(self) -> None: self.i: List[int] = [0] def foo(self, a: int, b: str) -> Dict[int, str]: return {a: b} foo = Foo() foo.x = 123 print(foo.x) print(foo.i) print(Foo.y) print(foo.foo(1, "abc")) 3# errors will not be detected until runtime $ python fib.py Traceback (most recent call last): File "fib.py", line 8, in7 đầu ra # errors will not be detected until runtime $ python fib.py Traceback (most recent call last): File "fib.py", line 8, in8 tuyên bố rõ ràng # errors will not be detected until runtime $ python fib.py Traceback (most recent call last): File "fib.py", line 8, in9 đầu ra # give a type hint from typing import Generator def fib(n: int) -> Generator: a: int = 0 b: int = 1 for _ in range(n): yield a b, a = a + b, b print([n for n in fib(3.6)])0 Cẩn thận khi đúc# give a type hint from typing import Generator def fib(n: int) -> Generator: a: int = 0 b: int = 1 for _ in range(n): yield a b, a = a + b, b print([n for n in fib(3.6)])1 đầu ra # give a type hint from typing import Generator def fib(n: int) -> Generator: a: int = 0 b: int = 1 for _ in range(n): yield a b, a = a + b, b print([n for n in fib(3.6)])2 Chuyển tiếp tài liệu tham khảoDựa trên PEP 484, nếu chúng tôi muốn tham chiếu một loại trước khi nó được khai báo, chúng tôi phải sử dụng chuỗi ký tự để ngụ ý rằng có một loại tên đó sau này trong tệp # give a type hint from typing import Generator def fib(n: int) -> Generator: a: int = 0 b: int = 1 for _ in range(n): yield a b, a = a + b, b print([n for n in fib(3.6)])3 Ghi chú Có một số vấn đề mà mypy không phàn nàn Forward References. Nhận thêm thông tin từ Số phát hành #948 # give a type hint from typing import Generator def fib(n: int) -> Generator: a: int = 0 b: int = 1 for _ in range(n): yield a b, a = a + b, b print([n for n in fib(3.6)])4 đầu ra # give a type hint from typing import Generator def fib(n: int) -> Generator: a: int = 0 b: int = 1 for _ in range(n): yield a b, a = a + b, b print([n for n in fib(3.6)])5 Hoãn đánh giá các chú thíchMới trong Python 3. 7
Trước Python 3. 7 # give a type hint from typing import Generator def fib(n: int) -> Generator: a: int = 0 b: int = 1 for _ in range(n): yield a b, a = a + b, b print([n for n in fib(3.6)])6 Sau Python 3. 7 (bao gồm 3. 7) # give a type hint from typing import Generator def fib(n: int) -> Generator: a: int = 0 b: int = 1 for _ in range(n): yield a b, a = a + b, b print([n for n in fib(3.6)])7 Ghi chú Chú thích chỉ có thể được sử dụng trong phạm vi tên đã tồn tại. Do đó, tham chiếu chuyển tiếp không hỗ trợ trường hợp tên không có sẵn trong phạm vi hiện tại. Đánh giá chú thích bị trì hoãn sẽ trở thành hành vi mặc định trong Python 4. 0 Nhập bí danhGiống như from typing import Generator # Generator[YieldType, SendType, ReturnType] def fib(n: int) -> Generator[int, None, None]: a: int = 0 b: int = 1 while n > 0: yield a b, a = a + b, b n -= 1 g: Generator = fib(10) i: Iterator[int] = (x for x in range(3))2 hoặc from typing import Generator # Generator[YieldType, SendType, ReturnType] def fib(n: int) -> Generator[int, None, None]: a: int = 0 b: int = 1 while n > 0: yield a b, a = a + b, b n -= 1 g: Generator = fib(10) i: Iterator[int] = (x for x in range(3))3 trong c/C++ # give a type hint from typing import Generator def fib(n: int) -> Generator: a: int = 0 b: int = 1 for _ in range(n): yield a b, a = a + b, b print([n for n in fib(3.6)])8 Bí danh loại được xác định bởi các phép gán biến đơn giản # give a type hint from typing import Generator def fib(n: int) -> Generator: a: int = 0 b: int = 1 for _ in range(n): yield a b, a = a + b, b print([n for n in fib(3.6)])9 Xác định một from typing import ClassVar, Dict, List class Foo: x: int = 1 # instance variable. default = 1 y: ClassVar[str] = "class var" # class variable def __init__(self) -> None: self.i: List[int] = [0] def foo(self, a: int, b: str) -> Dict[int, str]: return {a: b} foo = Foo() foo.x = 123 print(foo.x) print(foo.i) print(Foo.y) print(foo.foo(1, "abc")) 4Không giống như bí danh, from typing import ClassVar, Dict, List class Foo: x: int = 1 # instance variable. default = 1 y: ClassVar[str] = "class var" # class variable def __init__(self) -> None: self.i: List[int] = [0] def foo(self, a: int, b: str) -> Dict[int, str]: return {a: b} foo = Foo() foo.x = 123 print(foo.x) print(foo.i) print(Foo.y) print(foo.foo(1, "abc"))4 trả về một loại riêng biệt nhưng giống hệt với loại ban đầu khi chạy # errors will be detected before running $ mypy --strict fib.py fib.py:12: error: Argument 1 to "fib" has incompatible type "float"; expected "int"0 đầu ra # errors will be detected before running $ mypy --strict fib.py fib.py:12: error: Argument 1 to "fib" has incompatible type "float"; expected "int"1 đọc thêm
Sử dụng from typing import ClassVar, Dict, List class Foo: x: int = 1 # instance variable. default = 1 y: ClassVar[str] = "class var" # class variable def __init__(self) -> None: self.i: List[int] = [0] def foo(self, a: int, b: str) -> Dict[int, str]: return {a: b} foo = Foo() foo.x = 123 print(foo.x) print(foo.i) print(Foo.y) print(foo.foo(1, "abc")) 5 làm mẫuGiống như c ++ from typing import Generator # Generator[YieldType, SendType, ReturnType] def fib(n: int) -> Generator[int, None, None]: a: int = 0 b: int = 1 while n > 0: yield a b, a = a + b, b n -= 1 g: Generator = fib(10) i: Iterator[int] = (x for x in range(3))7 # errors will be detected before running $ mypy --strict fib.py fib.py:12: error: Argument 1 to "fib" has incompatible type "float"; expected "int"2 Python sử dụng from typing import ClassVar, Dict, List class Foo: x: int = 1 # instance variable. default = 1 y: ClassVar[str] = "class var" # class variable def __init__(self) -> None: self.i: List[int] = [0] def foo(self, a: int, b: str) -> Dict[int, str]: return {a: b} foo = Foo() foo.x = 123 print(foo.x) print(foo.i) print(Foo.y) print(foo.foo(1, "abc"))5 # errors will be detected before running $ mypy --strict fib.py fib.py:12: error: Argument 1 to "fib" has incompatible type "float"; expected "int"3 Sử dụng from typing import ClassVar, Dict, List class Foo: x: int = 1 # instance variable. default = 1 y: ClassVar[str] = "class var" # class variable def __init__(self) -> None: self.i: List[int] = [0] def foo(self, a: int, b: str) -> Dict[int, str]: return {a: b} foo = Foo() foo.x = 123 print(foo.x) print(foo.i) print(Foo.y) print(foo.foo(1, "abc")) 5 và from typing import ClassVar, Dict, List class Foo: x: int = 1 # instance variable. default = 1 y: ClassVar[str] = "class var" # class variable def __init__(self) -> None: self.i: List[int] = [0] def foo(self, a: int, b: str) -> Dict[int, str]: return {a: b} foo = Foo() foo.x = 123 print(foo.x) print(foo.i) print(Foo.y) print(foo.foo(1, "abc")) 7 làm mẫu lớp họcGiống như c ++ import asyncio from typing import AsyncGenerator, AsyncIterator async def fib(n: int) -> AsyncGenerator: a: int = 0 b: int = 1 while n > 0: await asyncio.sleep(0.1) yield a b, a = a + b, b n -= 1 async def main() -> None: async for f in fib(10): print(f) ag: AsyncIterator = (f async for f in fib(10)) loop = asyncio.get_event_loop() loop.run_until_complete(main())1 # errors will be detected before running $ mypy --strict fib.py fib.py:12: error: Argument 1 to "fib" has incompatible type "float"; expected "int"4 Định nghĩa một lớp chung trong Python # errors will be detected before running $ mypy --strict fib.py fib.py:12: error: Argument 1 to "fib" has incompatible type "float"; expected "int"5 đầu ra # errors will be detected before running $ mypy --strict fib.py fib.py:12: error: Argument 1 to "fib" has incompatible type "float"; expected "int"6 Quy tắc phạm vi cho from typing import ClassVar, Dict, List class Foo: x: int = 1 # instance variable. default = 1 y: ClassVar[str] = "class var" # class variable def __init__(self) -> None: self.i: List[int] = [0] def foo(self, a: int, b: str) -> Dict[int, str]: return {a: b} foo = Foo() foo.x = 123 print(foo.x) print(foo.i) print(Foo.y) print(foo.foo(1, "abc")) 5
# errors will be detected before running $ mypy --strict fib.py fib.py:12: error: Argument 1 to "fib" has incompatible type "float"; expected "int"7 đầu ra # errors will be detected before running $ mypy --strict fib.py fib.py:12: error: Argument 1 to "fib" has incompatible type "float"; expected "int"8
# errors will be detected before running $ mypy --strict fib.py fib.py:12: error: Argument 1 to "fib" has incompatible type "float"; expected "int"9 đầu ra import io import re from collections import deque, namedtuple from typing import ( Dict, List, Tuple, Set, Deque, NamedTuple, IO, Pattern, Match, Text, Optional, Sequence, Iterable, Mapping, MutableMapping, Any, ) # without initializing x: int # any type y: Any y = 1 y = "1" # built-in var_int: int = 1 var_str: str = "Hello Typing" var_byte: bytes = b"Hello Typing" var_bool: bool = True var_float: float = 1. var_unicode: Text = u'\u2713' # could be none var_could_be_none: Optional[int] = None var_could_be_none = 1 # collections var_set: Set[int] = {i for i in range(3)} var_dict: Dict[str, str] = {"foo": "Foo"} var_list: List[int] = [i for i in range(3)] var_static_length_Tuple: Tuple[int, int, int] = (1, 2, 3) var_dynamic_length_Tuple: Tuple[int, ...] = (i for i in range(10, 3)) var_deque: Deque = deque([1, 2, 3]) var_nametuple: NamedTuple = namedtuple('P', ['x', 'y']) # io var_io_str: IO[str] = io.StringIO("Hello String") var_io_byte: IO[bytes] = io.BytesIO(b"Hello Bytes") var_io_file_str: IO[str] = open(__file__) var_io_file_byte: IO[bytes] = open(__file__, 'rb') # re p: Pattern = re.compile("(https?)://([^/\r\n]+)(/[^\r\n]*)?") m: Optional[Match] = p.match("https://www.python.org/") # duck types: list-like var_seq_list: Sequence[int] = [1, 2, 3] var_seq_tuple: Sequence[int] = (1, 2, 3) var_iter_list: Iterable[int] = [1, 2, 3] var_iter_tuple: Iterable[int] = (1, 2, 3) # duck types: dict-like var_map_dict: Mapping[str, str] = {"foo": "Foo"} var_mutable_dict: MutableMapping[str, str] = {"bar": "Bar"}0
import io import re from collections import deque, namedtuple from typing import ( Dict, List, Tuple, Set, Deque, NamedTuple, IO, Pattern, Match, Text, Optional, Sequence, Iterable, Mapping, MutableMapping, Any, ) # without initializing x: int # any type y: Any y = 1 y = "1" # built-in var_int: int = 1 var_str: str = "Hello Typing" var_byte: bytes = b"Hello Typing" var_bool: bool = True var_float: float = 1. var_unicode: Text = u'\u2713' # could be none var_could_be_none: Optional[int] = None var_could_be_none = 1 # collections var_set: Set[int] = {i for i in range(3)} var_dict: Dict[str, str] = {"foo": "Foo"} var_list: List[int] = [i for i in range(3)] var_static_length_Tuple: Tuple[int, int, int] = (1, 2, 3) var_dynamic_length_Tuple: Tuple[int, ...] = (i for i in range(10, 3)) var_deque: Deque = deque([1, 2, 3]) var_nametuple: NamedTuple = namedtuple('P', ['x', 'y']) # io var_io_str: IO[str] = io.StringIO("Hello String") var_io_byte: IO[bytes] = io.BytesIO(b"Hello Bytes") var_io_file_str: IO[str] = open(__file__) var_io_file_byte: IO[bytes] = open(__file__, 'rb') # re p: Pattern = re.compile("(https?)://([^/\r\n]+)(/[^\r\n]*)?") m: Optional[Match] = p.match("https://www.python.org/") # duck types: list-like var_seq_list: Sequence[int] = [1, 2, 3] var_seq_tuple: Sequence[int] = (1, 2, 3) var_iter_list: Iterable[int] = [1, 2, 3] var_iter_tuple: Iterable[int] = (1, 2, 3) # duck types: dict-like var_map_dict: Mapping[str, str] = {"foo": "Foo"} var_mutable_dict: MutableMapping[str, str] = {"bar": "Bar"}1 đầu ra import io import re from collections import deque, namedtuple from typing import ( Dict, List, Tuple, Set, Deque, NamedTuple, IO, Pattern, Match, Text, Optional, Sequence, Iterable, Mapping, MutableMapping, Any, ) # without initializing x: int # any type y: Any y = 1 y = "1" # built-in var_int: int = 1 var_str: str = "Hello Typing" var_byte: bytes = b"Hello Typing" var_bool: bool = True var_float: float = 1. var_unicode: Text = u'\u2713' # could be none var_could_be_none: Optional[int] = None var_could_be_none = 1 # collections var_set: Set[int] = {i for i in range(3)} var_dict: Dict[str, str] = {"foo": "Foo"} var_list: List[int] = [i for i in range(3)] var_static_length_Tuple: Tuple[int, int, int] = (1, 2, 3) var_dynamic_length_Tuple: Tuple[int, ...] = (i for i in range(10, 3)) var_deque: Deque = deque([1, 2, 3]) var_nametuple: NamedTuple = namedtuple('P', ['x', 'y']) # io var_io_str: IO[str] = io.StringIO("Hello String") var_io_byte: IO[bytes] = io.BytesIO(b"Hello Bytes") var_io_file_str: IO[str] = open(__file__) var_io_file_byte: IO[bytes] = open(__file__, 'rb') # re p: Pattern = re.compile("(https?)://([^/\r\n]+)(/[^\r\n]*)?") m: Optional[Match] = p.match("https://www.python.org/") # duck types: list-like var_seq_list: Sequence[int] = [1, 2, 3] var_seq_tuple: Sequence[int] = (1, 2, 3) var_iter_list: Iterable[int] = [1, 2, 3] var_iter_tuple: Iterable[int] = (1, 2, 3) # duck types: dict-like var_map_dict: Mapping[str, str] = {"foo": "Foo"} var_mutable_dict: MutableMapping[str, str] = {"bar": "Bar"}2
import io import re from collections import deque, namedtuple from typing import ( Dict, List, Tuple, Set, Deque, NamedTuple, IO, Pattern, Match, Text, Optional, Sequence, Iterable, Mapping, MutableMapping, Any, ) # without initializing x: int # any type y: Any y = 1 y = "1" # built-in var_int: int = 1 var_str: str = "Hello Typing" var_byte: bytes = b"Hello Typing" var_bool: bool = True var_float: float = 1. var_unicode: Text = u'\u2713' # could be none var_could_be_none: Optional[int] = None var_could_be_none = 1 # collections var_set: Set[int] = {i for i in range(3)} var_dict: Dict[str, str] = {"foo": "Foo"} var_list: List[int] = [i for i in range(3)] var_static_length_Tuple: Tuple[int, int, int] = (1, 2, 3) var_dynamic_length_Tuple: Tuple[int, ...] = (i for i in range(10, 3)) var_deque: Deque = deque([1, 2, 3]) var_nametuple: NamedTuple = namedtuple('P', ['x', 'y']) # io var_io_str: IO[str] = io.StringIO("Hello String") var_io_byte: IO[bytes] = io.BytesIO(b"Hello Bytes") var_io_file_str: IO[str] = open(__file__) var_io_file_byte: IO[bytes] = open(__file__, 'rb') # re p: Pattern = re.compile("(https?)://([^/\r\n]+)(/[^\r\n]*)?") m: Optional[Match] = p.match("https://www.python.org/") # duck types: list-like var_seq_list: Sequence[int] = [1, 2, 3] var_seq_tuple: Sequence[int] = (1, 2, 3) var_iter_list: Iterable[int] = [1, 2, 3] var_iter_tuple: Iterable[int] = (1, 2, 3) # duck types: dict-like var_map_dict: Mapping[str, str] = {"foo": "Foo"} var_mutable_dict: MutableMapping[str, str] = {"bar": "Bar"}3 đầu ra import io import re from collections import deque, namedtuple from typing import ( Dict, List, Tuple, Set, Deque, NamedTuple, IO, Pattern, Match, Text, Optional, Sequence, Iterable, Mapping, MutableMapping, Any, ) # without initializing x: int # any type y: Any y = 1 y = "1" # built-in var_int: int = 1 var_str: str = "Hello Typing" var_byte: bytes = b"Hello Typing" var_bool: bool = True var_float: float = 1. var_unicode: Text = u'\u2713' # could be none var_could_be_none: Optional[int] = None var_could_be_none = 1 # collections var_set: Set[int] = {i for i in range(3)} var_dict: Dict[str, str] = {"foo": "Foo"} var_list: List[int] = [i for i in range(3)] var_static_length_Tuple: Tuple[int, int, int] = (1, 2, 3) var_dynamic_length_Tuple: Tuple[int, ...] = (i for i in range(10, 3)) var_deque: Deque = deque([1, 2, 3]) var_nametuple: NamedTuple = namedtuple('P', ['x', 'y']) # io var_io_str: IO[str] = io.StringIO("Hello String") var_io_byte: IO[bytes] = io.BytesIO(b"Hello Bytes") var_io_file_str: IO[str] = open(__file__) var_io_file_byte: IO[bytes] = open(__file__, 'rb') # re p: Pattern = re.compile("(https?)://([^/\r\n]+)(/[^\r\n]*)?") m: Optional[Match] = p.match("https://www.python.org/") # duck types: list-like var_seq_list: Sequence[int] = [1, 2, 3] var_seq_tuple: Sequence[int] = (1, 2, 3) var_iter_list: Iterable[int] = [1, 2, 3] var_iter_tuple: Iterable[int] = (1, 2, 3) # duck types: dict-like var_map_dict: Mapping[str, str] = {"foo": "Foo"} var_mutable_dict: MutableMapping[str, str] = {"bar": "Bar"}4 Hạn chế trong một tập hợp cố định các loại có thểimport asyncio from typing import AsyncGenerator, AsyncIterator async def fib(n: int) -> AsyncGenerator: a: int = 0 b: int = 1 while n > 0: await asyncio.sleep(0.1) yield a b, a = a + b, b n -= 1 async def main() -> None: async for f in fib(10): print(f) ag: AsyncIterator = (f async for f in fib(10)) loop = asyncio.get_event_loop() loop.run_until_complete(main())8 có nghĩa là chúng tôi tạo một biến loại có giới hạn giá trị import io import re from collections import deque, namedtuple from typing import ( Dict, List, Tuple, Set, Deque, NamedTuple, IO, Pattern, Match, Text, Optional, Sequence, Iterable, Mapping, MutableMapping, Any, ) # without initializing x: int # any type y: Any y = 1 y = "1" # built-in var_int: int = 1 var_str: str = "Hello Typing" var_byte: bytes = b"Hello Typing" var_bool: bool = True var_float: float = 1. var_unicode: Text = u'\u2713' # could be none var_could_be_none: Optional[int] = None var_could_be_none = 1 # collections var_set: Set[int] = {i for i in range(3)} var_dict: Dict[str, str] = {"foo": "Foo"} var_list: List[int] = [i for i in range(3)] var_static_length_Tuple: Tuple[int, int, int] = (1, 2, 3) var_dynamic_length_Tuple: Tuple[int, ...] = (i for i in range(10, 3)) var_deque: Deque = deque([1, 2, 3]) var_nametuple: NamedTuple = namedtuple('P', ['x', 'y']) # io var_io_str: IO[str] = io.StringIO("Hello String") var_io_byte: IO[bytes] = io.BytesIO(b"Hello Bytes") var_io_file_str: IO[str] = open(__file__) var_io_file_byte: IO[bytes] = open(__file__, 'rb') # re p: Pattern = re.compile("(https?)://([^/\r\n]+)(/[^\r\n]*)?") m: Optional[Match] = p.match("https://www.python.org/") # duck types: list-like var_seq_list: Sequence[int] = [1, 2, 3] var_seq_tuple: Sequence[int] = (1, 2, 3) var_iter_list: Iterable[int] = [1, 2, 3] var_iter_tuple: Iterable[int] = (1, 2, 3) # duck types: dict-like var_map_dict: Mapping[str, str] = {"foo": "Foo"} var_mutable_dict: MutableMapping[str, str] = {"bar": "Bar"}5 đầu ra import io import re from collections import deque, namedtuple from typing import ( Dict, List, Tuple, Set, Deque, NamedTuple, IO, Pattern, Match, Text, Optional, Sequence, Iterable, Mapping, MutableMapping, Any, ) # without initializing x: int # any type y: Any y = 1 y = "1" # built-in var_int: int = 1 var_str: str = "Hello Typing" var_byte: bytes = b"Hello Typing" var_bool: bool = True var_float: float = 1. var_unicode: Text = u'\u2713' # could be none var_could_be_none: Optional[int] = None var_could_be_none = 1 # collections var_set: Set[int] = {i for i in range(3)} var_dict: Dict[str, str] = {"foo": "Foo"} var_list: List[int] = [i for i in range(3)] var_static_length_Tuple: Tuple[int, int, int] = (1, 2, 3) var_dynamic_length_Tuple: Tuple[int, ...] = (i for i in range(10, 3)) var_deque: Deque = deque([1, 2, 3]) var_nametuple: NamedTuple = namedtuple('P', ['x', 'y']) # io var_io_str: IO[str] = io.StringIO("Hello String") var_io_byte: IO[bytes] = io.BytesIO(b"Hello Bytes") var_io_file_str: IO[str] = open(__file__) var_io_file_byte: IO[bytes] = open(__file__, 'rb') # re p: Pattern = re.compile("(https?)://([^/\r\n]+)(/[^\r\n]*)?") m: Optional[Match] = p.match("https://www.python.org/") # duck types: list-like var_seq_list: Sequence[int] = [1, 2, 3] var_seq_tuple: Sequence[int] = (1, 2, 3) var_iter_list: Iterable[int] = [1, 2, 3] var_iter_tuple: Iterable[int] = (1, 2, 3) # duck types: dict-like var_map_dict: Mapping[str, str] = {"foo": "Foo"} var_mutable_dict: MutableMapping[str, str] = {"bar": "Bar"}6 from typing import ClassVar, Dict, List class Foo: x: int = 1 # instance variable. default = 1 y: ClassVar[str] = "class var" # class variable def __init__(self) -> None: self.i: List[int] = [0] def foo(self, a: int, b: str) -> Dict[int, str]: return {a: b} foo = Foo() foo.x = 123 print(foo.x) print(foo.i) print(Foo.y) print(foo.foo(1, "abc")) 5 với giới hạn trênfrom typing import ContextManager, Generator, IO from contextlib import contextmanager @contextmanager def open_file(name: str) -> Generator: f = open(name) yield f f.close() cm: ContextManager[IO] = open_file(__file__) with cm as f: print(f.read())0 có nghĩa là chúng ta tạo một biến kiểu có giới hạn trên. Khái niệm này tương tự như tính đa hình trong C++ import io import re from collections import deque, namedtuple from typing import ( Dict, List, Tuple, Set, Deque, NamedTuple, IO, Pattern, Match, Text, Optional, Sequence, Iterable, Mapping, MutableMapping, Any, ) # without initializing x: int # any type y: Any y = 1 y = "1" # built-in var_int: int = 1 var_str: str = "Hello Typing" var_byte: bytes = b"Hello Typing" var_bool: bool = True var_float: float = 1. var_unicode: Text = u'\u2713' # could be none var_could_be_none: Optional[int] = None var_could_be_none = 1 # collections var_set: Set[int] = {i for i in range(3)} var_dict: Dict[str, str] = {"foo": "Foo"} var_list: List[int] = [i for i in range(3)] var_static_length_Tuple: Tuple[int, int, int] = (1, 2, 3) var_dynamic_length_Tuple: Tuple[int, ...] = (i for i in range(10, 3)) var_deque: Deque = deque([1, 2, 3]) var_nametuple: NamedTuple = namedtuple('P', ['x', 'y']) # io var_io_str: IO[str] = io.StringIO("Hello String") var_io_byte: IO[bytes] = io.BytesIO(b"Hello Bytes") var_io_file_str: IO[str] = open(__file__) var_io_file_byte: IO[bytes] = open(__file__, 'rb') # re p: Pattern = re.compile("(https?)://([^/\r\n]+)(/[^\r\n]*)?") m: Optional[Match] = p.match("https://www.python.org/") # duck types: list-like var_seq_list: Sequence[int] = [1, 2, 3] var_seq_tuple: Sequence[int] = (1, 2, 3) var_iter_list: Iterable[int] = [1, 2, 3] var_iter_tuple: Iterable[int] = (1, 2, 3) # duck types: dict-like var_map_dict: Mapping[str, str] = {"foo": "Foo"} var_mutable_dict: MutableMapping[str, str] = {"bar": "Bar"}7 Giống như c++, tạo một lớp cơ sở và from typing import ClassVar, Dict, List class Foo: x: int = 1 # instance variable. default = 1 y: ClassVar[str] = "class var" # class variable def __init__(self) -> None: self.i: List[int] = [0] def foo(self, a: int, b: str) -> Dict[int, str]: return {a: b} foo = Foo() foo.x = 123 print(foo.x) print(foo.i) print(Foo.y) print(foo.foo(1, "abc"))5 liên kết với lớp cơ sở. Sau đó, trình kiểm tra kiểu tĩnh sẽ lấy mọi lớp con làm kiểu lớp cơ sở import io import re from collections import deque, namedtuple from typing import ( Dict, List, Tuple, Set, Deque, NamedTuple, IO, Pattern, Match, Text, Optional, Sequence, Iterable, Mapping, MutableMapping, Any, ) # without initializing x: int # any type y: Any y = 1 y = "1" # built-in var_int: int = 1 var_str: str = "Hello Typing" var_byte: bytes = b"Hello Typing" var_bool: bool = True var_float: float = 1. var_unicode: Text = u'\u2713' # could be none var_could_be_none: Optional[int] = None var_could_be_none = 1 # collections var_set: Set[int] = {i for i in range(3)} var_dict: Dict[str, str] = {"foo": "Foo"} var_list: List[int] = [i for i in range(3)] var_static_length_Tuple: Tuple[int, int, int] = (1, 2, 3) var_dynamic_length_Tuple: Tuple[int, ...] = (i for i in range(10, 3)) var_deque: Deque = deque([1, 2, 3]) var_nametuple: NamedTuple = namedtuple('P', ['x', 'y']) # io var_io_str: IO[str] = io.StringIO("Hello String") var_io_byte: IO[bytes] = io.BytesIO(b"Hello Bytes") var_io_file_str: IO[str] = open(__file__) var_io_file_byte: IO[bytes] = open(__file__, 'rb') # re p: Pattern = re.compile("(https?)://([^/\r\n]+)(/[^\r\n]*)?") m: Optional[Match] = p.match("https://www.python.org/") # duck types: list-like var_seq_list: Sequence[int] = [1, 2, 3] var_seq_tuple: Sequence[int] = (1, 2, 3) var_iter_list: Iterable[int] = [1, 2, 3] var_iter_tuple: Iterable[int] = (1, 2, 3) # duck types: dict-like var_map_dict: Mapping[str, str] = {"foo": "Foo"} var_mutable_dict: MutableMapping[str, str] = {"bar": "Bar"}8 đầu ra import io import re from collections import deque, namedtuple from typing import ( Dict, List, Tuple, Set, Deque, NamedTuple, IO, Pattern, Match, Text, Optional, Sequence, Iterable, Mapping, MutableMapping, Any, ) # without initializing x: int # any type y: Any y = 1 y = "1" # built-in var_int: int = 1 var_str: str = "Hello Typing" var_byte: bytes = b"Hello Typing" var_bool: bool = True var_float: float = 1. var_unicode: Text = u'\u2713' # could be none var_could_be_none: Optional[int] = None var_could_be_none = 1 # collections var_set: Set[int] = {i for i in range(3)} var_dict: Dict[str, str] = {"foo": "Foo"} var_list: List[int] = [i for i in range(3)] var_static_length_Tuple: Tuple[int, int, int] = (1, 2, 3) var_dynamic_length_Tuple: Tuple[int, ...] = (i for i in range(10, 3)) var_deque: Deque = deque([1, 2, 3]) var_nametuple: NamedTuple = namedtuple('P', ['x', 'y']) # io var_io_str: IO[str] = io.StringIO("Hello String") var_io_byte: IO[bytes] = io.BytesIO(b"Hello Bytes") var_io_file_str: IO[str] = open(__file__) var_io_file_byte: IO[bytes] = open(__file__, 'rb') # re p: Pattern = re.compile("(https?)://([^/\r\n]+)(/[^\r\n]*)?") m: Optional[Match] = p.match("https://www.python.org/") # duck types: list-like var_seq_list: Sequence[int] = [1, 2, 3] var_seq_tuple: Sequence[int] = (1, 2, 3) var_iter_list: Iterable[int] = [1, 2, 3] var_iter_tuple: Iterable[int] = (1, 2, 3) # duck types: dict-like var_map_dict: Mapping[str, str] = {"foo": "Foo"} var_mutable_dict: MutableMapping[str, str] = {"bar": "Bar"}9 @overloadĐôi khi, chúng tôi sử dụng from typing import ContextManager, Generator, IO from contextlib import contextmanager @contextmanager def open_file(name: str) -> Generator: f = open(name) yield f f.close() cm: ContextManager[IO] = open_file(__file__) with cm as f: print(f.read())2 để suy ra rằng trả về của hàm có nhiều loại khác nhau. Tuy nhiên, trình kiểm tra loại không thể phân biệt loại nào chúng ta muốn. Do đó, đoạn mã sau cho thấy trình kiểm tra loại không thể xác định loại nào là đúng from typing import Generator, Callable # function def gcd(a: int, b: int) -> int: while b: a, b = b, a % b return a # callback def fun(cb: Callable[[int, int], int]) -> int: return cb(55, 66) # lambda f: Callable[[int], int] = lambda x: x * 20 đầu ra from typing import Generator, Callable # function def gcd(a: int, b: int) -> int: while b: a, b = b, a % b return a # callback def fun(cb: Callable[[int, int], int]) -> int: return cb(55, 66) # lambda f: Callable[[int], int] = lambda x: x * 21 Mặc dù chúng ta có thể sử dụng from typing import ContextManager, Generator, IO from contextlib import contextmanager @contextmanager def open_file(name: str) -> Generator: f = open(name) yield f f.close() cm: ContextManager[IO] = open_file(__file__) with cm as f: print(f.read())3 để giải quyết vấn đề nhưng nó không tránh khỏi lỗi đánh máy và from typing import ContextManager, Generator, IO from contextlib import contextmanager @contextmanager def open_file(name: str) -> Generator: f = open(name) yield f f.close() cm: ContextManager[IO] = open_file(__file__) with cm as f: print(f.read())3 không an toàn from typing import Generator, Callable # function def gcd(a: int, b: int) -> int: while b: a, b = b, a % b return a # callback def fun(cb: Callable[[int, int], int]) -> int: return cb(55, 66) # lambda f: Callable[[int], int] = lambda x: x * 22 đầu ra from typing import Generator, Callable # function def gcd(a: int, b: int) -> int: while b: a, b = b, a % b return a # callback def fun(cb: Callable[[int, int], int]) -> int: return cb(55, 66) # lambda f: Callable[[int], int] = lambda x: x * 23 Sử dụng from typing import ContextManager, Generator, IO from contextlib import contextmanager @contextmanager def open_file(name: str) -> Generator: f = open(name) yield f f.close() cm: ContextManager[IO] = open_file(__file__) with cm as f: print(f.read())5 có thể giải quyết vấn đề. Chúng ta có thể khai báo kiểu trả về một cách rõ ràng from typing import Generator, Callable # function def gcd(a: int, b: int) -> int: while b: a, b = b, a % b return a # callback def fun(cb: Callable[[int, int], int]) -> int: return cb(55, 66) # lambda f: Callable[[int], int] = lambda x: x * 24 đầu ra from typing import Generator, Callable # function def gcd(a: int, b: int) -> int: while b: a, b = b, a % b return a # callback def fun(cb: Callable[[int, int], int]) -> int: return cb(55, 66) # lambda f: Callable[[int], int] = lambda x: x * 23 Cảnh báo Dựa trên PEP 484, trình trang trí from typing import ContextManager, Generator, IO from contextlib import contextmanager @contextmanager def open_file(name: str) -> Generator: f = open(name) yield f f.close() cm: ContextManager[IO] = open_file(__file__) with cm as f: print(f.read())5 chỉ dành cho trình kiểm tra kiểu, nó không triển khai quá tải thực sự như c++/java. Vì vậy, chúng ta phải triển khai một chức năng chính xác không phải ____9_______5. Trong thời gian chạy, gọi hàm from typing import ContextManager, Generator, IO from contextlib import contextmanager @contextmanager def open_file(name: str) -> Generator: f = open(name) yield f f.close() cm: ContextManager[IO] = open_file(__file__) with cm as f: print(f.read())5 sẽ tăng from typing import ContextManager, Generator, IO from contextlib import contextmanager @contextmanager def open_file(name: str) -> Generator: f = open(name) yield f f.close() cm: ContextManager[IO] = open_file(__file__) with cm as f: print(f.read())9 from typing import Generator, Callable # function def gcd(a: int, b: int) -> int: while b: a, b = b, a % b return a # callback def fun(cb: Callable[[int, int], int]) -> int: return cb(55, 66) # lambda f: Callable[[int], int] = lambda x: x * 26 đầu ra from typing import Generator, Callable # function def gcd(a: int, b: int) -> int: while b: a, b = b, a % b return a # callback def fun(cb: Callable[[int, int], int]) -> int: return cb(55, 66) # lambda f: Callable[[int], int] = lambda x: x * 27 Tập tin sơ khaiCác tệp sơ khai giống như các tệp tiêu đề mà chúng ta thường sử dụng để xác định giao diện của mình trong c/C++. Trong python, chúng ta có thể định nghĩa các giao diện của mình trong cùng một thư mục mô-đun hoặc # errors will not be detected until runtime $ python fib.py Traceback (most recent call last): File "fib.py", line 8, in00 Việc sử dụng gõ trong Python là gì?Python hỗ trợ khái niệm gõ dần dần. Điều này có nghĩa là bạn có thể dần đưa các loại vào mã của mình . Mã không có gợi ý loại sẽ bị trình kiểm tra loại tĩnh bỏ qua. Do đó, bạn có thể bắt đầu thêm các loại vào các thành phần quan trọng và tiếp tục miễn là nó tăng thêm giá trị cho bạn.
gõ mô-đun trong Python là gì?Được giới thiệu từ Python 3. 5, Mô-đun gõ của Python cố gắng cung cấp cách gợi ý các loại để giúp trình kiểm tra kiểu tĩnh và bộ lọc dự đoán chính xác lỗi .
Kiểu () trả về gì trong Python?Hàm type() dùng để lấy kiểu của một đối tượng. Khi một đối số duy nhất được chuyển đến hàm type(), nó sẽ trả về loại đối tượng . Giá trị của nó giống như đối tượng. |