Chỉ định một loại biếnCó thể có những lúc bạn muốn chỉ định một loại trên một biến. Điều này có thể được thực hiện với đúc. Python là một ngôn ngữ định hướng đối tượng và do đó, nó sử dụng các lớp để xác định các loại dữ liệu, bao gồm cả các loại nguyên thủy của nó. Show
Do đó, việc đúc trong Python được thực hiện bằng cách sử dụng các hàm xây dựng:
Thí dụIntegers: x = int (1) & nbsp; & nbsp; # x sẽ là 1 y = int (2.8) # y sẽ là 2 z = int ("3") # z sẽ là 3 Hãy tự mình thử » Thí dụFloats: x = int (1) & nbsp; & nbsp; # x sẽ là 1 y = int (2.8) # y sẽ là 2 z = int ("3") # z sẽ là 3 Hãy tự mình thử » Thí dụStrings: x = int (1) & nbsp; & nbsp; # x sẽ là 1 y = int (2.8) # y sẽ là 2 z = int ("3") # z sẽ là 3 Hãy tự mình thử » Python’s dynamism means that, although support continues to expand, type hints will never cover every situation. For edge cases we need to use an “escape hatch” to override the type checker. Một hatch thoát như vậy là nhận xét Một cái hatch thoát hiểm khác, chúng ta có thể sử dụng là đúc. Chúng ta có thể sử dụng rõ ràng với $ mypy example.py example.py:6: note: Revealed type is "builtins.int" example.py:8: note: Revealed type is "builtins.str"0 với các gợi ý loại. Với việc đúc, chúng tôi có thể buộc người kiểm tra loại để coi một biến là một loại nhất định. Hãy cùng xem xét cách chúng ta có thể sử dụng đúc rõ ràng và ẩn, và một tính năng MyPy để quản lý các cuộc gọi đến $ mypy example.py example.py:6: note: Revealed type is "builtins.int" example.py:8: note: Revealed type is "builtins.str"1. $ mypy example.py example.py:6: note: Revealed type is "builtins.int" example.py:8: note: Revealed type is "builtins.str" 1 đơn giản nhấtKhi chúng tôi gọi $ mypy example.py example.py:6: note: Revealed type is "builtins.int" example.py:8: note: Revealed type is "builtins.str"1, chúng tôi vượt qua hai đối số: một loại và một giá trị. $ mypy example.py example.py:6: note: Revealed type is "builtins.int" example.py:8: note: Revealed type is "builtins.str"1 Trả về $ mypy example.py example.py:6: note: Revealed type is "builtins.int" example.py:8: note: Revealed type is "builtins.str"5 Không thay đổi, nhưng người kiểm tra loại sẽ coi giá trị trả về là loại đã cho thay vì loại đầu vào. Ví dụ: chúng ta có thể biến Mypy coi một số nguyên như một chuỗi: from __future__ import annotations from typing import cast x = 1 reveal_type(x) y = cast(str, x) reveal_type(y) y.upper() Kiểm tra chương trình này với MyPy, nó không báo cáo bất kỳ lỗi nào, nhưng nó đã gỡ lỗi các loại $ mypy example.py example.py:6: note: Revealed type is "builtins.int" example.py:8: note: Revealed type is "builtins.str"6 và $ mypy example.py example.py:6: note: Revealed type is "builtins.int" example.py:8: note: Revealed type is "builtins.str"7 cho chúng tôi: $ mypy example.py example.py:6: note: Revealed type is "builtins.int" example.py:8: note: Revealed type is "builtins.str" Nhưng, nếu chúng tôi xóa các cuộc gọi $ mypy example.py example.py:6: note: Revealed type is "builtins.int" example.py:8: note: Revealed type is "builtins.str"8 và chạy mã, nó sẽ gặp sự cố: $ python example.py Traceback (most recent call last): File "/.../example.py", line 7, in <module> y.upper() AttributeError: 'int' object has no attribute 'upper' Thông thường MyPy sẽ phát hiện lỗi này, vì nó biết các đối tượng $ mypy example.py example.py:6: note: Revealed type is "builtins.int" example.py:8: note: Revealed type is "builtins.str"9 không có phương thức $ python example.py Traceback (most recent call last): File "/.../example.py", line 7, in <module> y.upper() AttributeError: 'int' object has no attribute 'upper'0. Nhưng $ mypy example.py example.py:6: note: Revealed type is "builtins.int" example.py:8: note: Revealed type is "builtins.str"1 của chúng tôi đã buộc Mypy phải coi $ mypy example.py example.py:6: note: Revealed type is "builtins.int" example.py:8: note: Revealed type is "builtins.str"7 là một $ python example.py Traceback (most recent call last): File "/.../example.py", line 7, in <module> y.upper() AttributeError: 'int' object has no attribute 'upper'3, vì vậy nó cho rằng cuộc gọi sẽ thành công. Trong thời gian chạy, $ mypy example.py example.py:6: note: Revealed type is "builtins.int" example.py:8: note: Revealed type is "builtins.str"1 thực sự không làm gì cả - hành vi đặc biệt của nó chỉ nằm trong cách kiểm tra loại diễn giải nó. Mã nguồn Python sườn tiết lộ $ mypy example.py example.py:6: note: Revealed type is "builtins.int" example.py:8: note: Revealed type is "builtins.str"1 là một cuộc gọi chức năng không có đơn giản: def cast(typ, val): """Cast a value to a type. This returns the value unchanged. To the type checker this signals that the return value has the designated type, but at runtime we intentionally don't check anything (we want this to be as fast as possible). """ return val Vì $ mypy example.py example.py:6: note: Revealed type is "builtins.int" example.py:8: note: Revealed type is "builtins.str"1 là một hàm Python bình thường, gọi nó mang theo một hình phạt hiệu suất thời gian rất nhẹ. Điều này rất hiếm khi là một vấn đề. Như thường lệ, bạn nên lập hồ sơ mã của mình trước khi đưa ra bất kỳ giả định nào về hiệu suất. Trường hợp sử dụngTrường hợp chính để đạt được $ mypy example.py example.py:6: note: Revealed type is "builtins.int" example.py:8: note: Revealed type is "builtins.str"1 là khi loại gợi ý cho một mô -đun bị thiếu, không đầy đủ hoặc không chính xác. Đây có thể là trường hợp cho các gói của bên thứ ba, hoặc đôi khi cho những thứ trong thư viện tiêu chuẩn. Lấy ví dụ này: import datetime as dt from typing import cast from third_party import get_data data = get_data() last_import_time = cast(dt.datetime, data["last_import_time"]) Hãy tưởng tượng $ python example.py Traceback (most recent call last): File "/.../example.py", line 7, in <module> y.upper() AttributeError: 'int' object has no attribute 'upper'8 có loại trở lại là $ python example.py Traceback (most recent call last): File "/.../example.py", line 7, in <module> y.upper() AttributeError: 'int' object has no attribute 'upper'9, thay vì sử dụng các loại KEY nghiêm ngặt hơn với def cast(typ, val): """Cast a value to a type. This returns the value unchanged. To the type checker this signals that the return value has the designated type, but at runtime we intentionally don't check anything (we want this to be as fast as possible). """ return val0. Từ việc đọc tài liệu hoặc nguồn, chúng tôi có thể thấy rằng khóa def cast(typ, val): """Cast a value to a type. This returns the value unchanged. To the type checker this signals that the return value has the designated type, but at runtime we intentionally don't check anything (we want this to be as fast as possible). """ return val1 luôn chứa đối tượng def cast(typ, val): """Cast a value to a type. This returns the value unchanged. To the type checker this signals that the return value has the designated type, but at runtime we intentionally don't check anything (we want this to be as fast as possible). """ return val2. Do đó, khi chúng tôi truy cập nó, chúng tôi có thể bọc nó trong một $ mypy example.py example.py:6: note: Revealed type is "builtins.int" example.py:8: note: Revealed type is "builtins.str"1, để nói với trình kiểm tra loại của chúng tôi loại thực thay vì tiếp tục với $ mypy example.py example.py:6: note: Revealed type is "builtins.int" example.py:8: note: Revealed type is "builtins.str"0. Khi chúng ta gặp phải các gợi ý loại thiếu, không đầy đủ hoặc không chính xác, chúng ta có thể đóng góp lại một bản sửa lỗi. Điều này có thể nằm trong gói, gói sơ khai liên quan của nó hoặc các cuống riêng biệt trong Python. Nhưng cho đến khi bản sửa lỗi như vậy được phát hành, chúng tôi sẽ cần sử dụng $ mypy example.py example.py:6: note: Revealed type is "builtins.int" example.py:8: note: Revealed type is "builtins.str"1 để kiểm tra loại mã mã của chúng tôi. Đúc ẩn từ $ mypy example.py example.py:6: note: Revealed type is "builtins.int" example.py:8: note: Revealed type is "builtins.str" 0Điều đáng chú ý là $ mypy example.py example.py:6: note: Revealed type is "builtins.int" example.py:8: note: Revealed type is "builtins.str"0 có cách xử lý đặc biệt: khi chúng tôi lưu trữ một biến có loại $ mypy example.py example.py:6: note: Revealed type is "builtins.int" example.py:8: note: Revealed type is "builtins.str"0 trong một biến với một loại cụ thể, loại kiểm tra loại coi đây là một diễn viên ngầm. Do đó, chúng ta có thể viết ví dụ trước mà không có $ mypy example.py example.py:6: note: Revealed type is "builtins.int" example.py:8: note: Revealed type is "builtins.str"1: import datetime as dt from third_party import get_data data = get_data() last_import_time: dt.datetime = data["last_import_time"] Kiểu đúc ngầm này là công cụ đầu tiên chúng ta nên tiếp cận khi tương tác với các thư viện trả về ____10. Nó cũng áp dụng khi chúng tôi vượt qua một biến được gõ $ mypy example.py example.py:6: note: Revealed type is "builtins.int" example.py:8: note: Revealed type is "builtins.str"0 dưới dạng đối số chức năng được gõ cụ thể hoặc giá trị trả về. Gọi $ mypy example.py example.py:6: note: Revealed type is "builtins.int" example.py:8: note: Revealed type is "builtins.str"1 trực tiếp thường hữu ích hơn khi xử lý các loại không chính xác ngoài $ mypy example.py example.py:6: note: Revealed type is "builtins.int" example.py:8: note: Revealed type is "builtins.str"0. Tùy chọn Mypy từ import datetime as dt from typing import cast from third_party import get_data data = get_data() last_import_time = cast(dt.datetime, data["last_import_time"]) 4Khi chúng tôi sử dụng $ mypy example.py example.py:6: note: Revealed type is "builtins.int" example.py:8: note: Revealed type is "builtins.str"1 để ghi đè loại chức năng của bên thứ ba, loại đó sẽ được sửa trong phiên bản sau (có lẽ từ PR của chúng tôi!). Sau khi cập nhật như vậy, $ mypy example.py example.py:6: note: Revealed type is "builtins.int" example.py:8: note: Revealed type is "builtins.str"1 là sự lộn xộn không cần thiết có thể gây nhầm lẫn cho độc giả. Chúng ta có thể phát hiện các diễn viên không cần thiết như vậy bằng cách kích hoạt tùy chọn MYPY import datetime as dt from typing import cast from third_party import get_data data = get_data() last_import_time = cast(dt.datetime, data["last_import_time"])4. Với cờ này được bật, MyPy sẽ ghi lại một lỗi cho mỗi lần sử dụng $ mypy example.py example.py:6: note: Revealed type is "builtins.int" example.py:8: note: Revealed type is "builtins.str"1 tạo ra một biến cho loại nó đã có. (Điều này cung cấp một kiểm tra độ sạch tương tự như import datetime as dt from typing import cast from third_party import get_data data = get_data() last_import_time = cast(dt.datetime, data["last_import_time"])9, mà tôi đã đề cập trước đó.) Ví dụ: lấy $ mypy example.py example.py:6: note: Revealed type is "builtins.int" example.py:8: note: Revealed type is "builtins.str"1 không cần thiết này: from typing import cast x = 1 y = cast(int, x) Chạy MyPy với tùy chọn hoạt động, chúng ta thấy lỗi này: $ mypy --warn-redundant-casts example.py example.py:6: error: Redundant cast to "int" Found 1 error in 1 file (checked 1 source file) Kích hoạt tùy chọn này là một người bảo vệ tuyệt vời để giữ cho các loại của chúng tôi sạch sẽ. VâyBây giờ don lồng đi $ mypy example.py example.py:6: note: Revealed type is "builtins.int" example.py:8: note: Revealed type is "builtins.str"1 rất nhiều! —Adam Nếu dự án Django của bạn, thử nghiệm dài chạy của bạn, tôi đã viết một cuốn sách có thể giúp ích. Một email tóm tắt một tuần, không spam, tôi pinky hứa. Bài viết liên quan:
Tags: Mypy, Python mypy, python Đúc trong Python có phải là một chức năng không?Như Cast () là một hàm Python bình thường, gọi nó mang theo một hình phạt hiệu suất thời gian rất nhẹ. Điều này rất hiếm khi là một vấn đề. Như thường lệ, bạn nên lập hồ sơ mã của mình trước khi đưa ra bất kỳ giả định nào về hiệu suất.cast() is a normal Python function, calling it does carry a very slight runtime performance penalty. This will very rarely be an issue. As usual, you should profile your code before making any assumptions about performance.
Tại sao cần phải đúc trong Python?Python tránh việc mất dữ liệu trong chuyển đổi loại ngầm.Chuyển đổi loại rõ ràng cũng được gọi là loại đúc, các loại dữ liệu của các đối tượng được chuyển đổi bằng các hàm được xác định trước của người dùng.Trong loại đúc, mất dữ liệu có thể xảy ra khi chúng tôi thực thi đối tượng đến một loại dữ liệu cụ thể.avoids the loss of data in Implicit Type Conversion. Explicit Type Conversion is also called Type Casting, the data types of objects are converted using predefined functions by the user. In Type Casting, loss of data may occur as we enforce the object to a specific data type.
Làm thế nào để bạn đúc một cái gì đó trong Python?Để chuyển đổi hoặc đúc, một chuỗi thành một số nguyên trong Python, bạn sử dụng hàm tích hợp int ().Hàm nhận được như một tham số, chuỗi ban đầu bạn muốn chuyển đổi và trả về số nguyên tương đương với giá trị bạn đã vượt qua.Cú pháp chung trông giống như thế này: int ("str").use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .
Loại đúc loại với ví dụ trong Python là gì?Việc chuyển đổi một loại dữ liệu thành loại dữ liệu khác được gọi là loại đúc trong python hoặc chuyển đổi loại trong Python.Python hỗ trợ nhiều chức năng hoặc phương thức khác nhau như: int (), float (), str (), ord (), hex (), oct (), tuple (), set (), list (), dict (), vv cho loại đúc trong Python. is known as type casting in python or type conversion in python. Python supports a wide variety of functions or methods like: int(), float(), str(), ord(), hex(), oct(), tuple(), set(), list(), dict(), etc. for the type casting in python. |