用法:
class typing.Type(Generic[CT_co])使用
C注釋的變量可以接受類型為C的值。相反,使用Type[C]注釋的變量可以接受本身就是類的值 - 具體來說,它將接受C的class object。例如:a = 3 # Has type 'int' b = int # Has type 'Type[int]' c = type(a) # Also has type 'Type[int]'請注意,
Type[C]是協變的:class User: ... class BasicUser(User): ... class ProUser(User): ... class TeamUser(User): ... # Accepts User, BasicUser, ProUser, TeamUser, ... def make_new_user(user_class: Type[User]) -> User: # ... return user_class()事實是
Type[C]是協變的意味著所有的子類C應該實現相同的構造函數簽名和類方法簽名C.類型檢查器應標記違反此規則的行為,但還應允許子類中的構造函數調用與指定基類中的構造函數調用匹配。類型檢查器如何處理這種特殊情況可能會在未來的修訂中發生變化PEP 484.Type的唯一合法參數是類、Any、類型變量和任何這些類型的聯合。例如:def new_non_team_user(user_class: Type[BasicUser | ProUser]): ...Type[Any]等價於Type,後者又等價於type,它是 Python 元類層次結構的根。版本 3.5.2 中的新函數。
相關用法
- Python typing.TypedDict.__optional_keys__用法及代碼示例
- Python typing.TypedDict.__total__用法及代碼示例
- Python typing.TypeVar用法及代碼示例
- Python typing.TypedDict用法及代碼示例
- Python typing.TypeGuard用法及代碼示例
- Python typing.TypeAlias用法及代碼示例
- Python typing.TYPE_CHECKING用法及代碼示例
- Python typing.get_type_hints用法及代碼示例
- Python typing.Concatenate用法及代碼示例
- Python typing.Optional用法及代碼示例
- Python typing.Final用法及代碼示例
- Python typing.Protocol用法及代碼示例
- Python typing.NoReturn用法及代碼示例
- Python typing.is_typeddict用法及代碼示例
- Python typing.AsyncGenerator用法及代碼示例
- Python typing.final用法及代碼示例
- Python typing.ClassVar用法及代碼示例
- Python typing.ParamSpec用法及代碼示例
- Python typing.Literal用法及代碼示例
- Python typing.overload用法及代碼示例
注:本文由純淨天空篩選整理自python.org大神的英文原創作品 typing.Type。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
