[英]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.