简体   繁体   English

用户定义的类型显式声明一个嵌套类型

[英]User-defined type declaring explicitly a nested type

I find it really useful to have Python types such as Dict[str, int] , which declare the types they contain and allow them to be type checked too. 我发现拥有诸如Dict[str, int]之类的Python类型非常有用,这些类型声明它们包含的类型并允许对其进行类型检查。 However I can't find how I can create such a type. 但是我找不到如何创建这样的类型。 If, for example, I write 例如,如果我写

    class Classy:
       def __init__(self, x: Any) -> None:
           self.value = x

how can I express it as Classy[int] , Classy[str] , Classy[List[int]] , etc? 如何将其表示为Classy[int]Classy[str]Classy[List[int]]等?

Use TypeVar() to declare type variable, and use Generic as base class. 使用TypeVar()声明类型变量,并使用Generic作为基类。

from typing import TypeVar, Generic
T = TypeVar('T')
class Classy(Generic[T]):
    def __init__(self, x: T) -> None:
        self.value = x
    def get_value(self) -> T:
        return self.value

You can try: 你可以试试:

class1 = Classy[int](100)
class2 = Classy[str]('abc')
print(class1.get_value())
print(class2.get_value())

Then you will see: 然后您将看到:

100
abc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python用户定义的数据类型 - Python User-Defined Data Type 在Python中明确声明变量类型 - Explicitly declaring a variable type in Python 使用用户定义的函数声明一个熊猫系列 - Declaring a pandas series with a user-defined function 对用户定义类型项的矩阵执行Numpy操作 - Perform Numpy operation on matrix of user-defined type items 用户定义的泛型类型别名(透明注解) - User-defined generic type alias (transparent annotation) 建立由包(numpy)引入的类型作为python中用户定义函数的定义输入参数之一 - Establishing type introduced by a package(numpy) as one of the defined input parameters of a user-defined function in python python 通用类型提示 + 用户定义的容器 + 限制实现 __add__ 方法的类型 - python Generic Type Hints + user-defined container + constraining to Types implementing __add__ method 将作为pyodbc游标的属性返回的所有字段追加到用户定义的数据类型 - Append all fields returned as attributes of a pyodbc cursor to a user-defined data type 用户定义类型的元类的__new__和__init__在哪里被调用? - where does a user-defined type's metaclass' __new__ and __init__ get invoked? Python-如何创建用户定义的函数以将整数转换为浮点型数字? - Python - How to create a user-defined function to convert an integer into a float-type number?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM