我正在尝试使用TypeVar将init参数指示为某种类型。但是我做错了,或者甚至没有可能。
from typing import TypeVar
T=TypeVar("T")
class TestClass:
def __init__(self,value:T):
self._value=value
a = TestClass(value=10)
b = TestClass(value="abc")
reveal_type(a._value)
reveal_type(b._value)
我希望的揭露类型是a._value
曾经int
和b._value
将会是string
。但是它们都显示为“ T`-1”
任何帮助或见解表示赞赏!
[编辑]
再扩展一点的例子。BaseClass将被覆盖,并且实际的类型提示由覆盖的类提供。
from typing import TypeVar
T=TypeVar("T")
class BaseClass:
def __init__(self,value):
self._value = value
class Class1(BaseClass):
def __init__(self,value:str):
super().__init__(value)
class Class2(BaseClass):
def __init__(self,value:int):
super().__init__(value)
a = Class1("A value")
b = Class2(10)
reveal_type(a._value)
reveal_type(b._value)
默认情况下,使用TypeVar只能将其范围限制为用作注释的方法/函数。为了将TypeVar限定于实例和所有方法/属性,请将类声明为Generic
。
from typing import TypeVar, Generic
T=TypeVar("T")
class BaseClass(Generic[T]): # Scope of `T` is the class:
def __init__(self, value: T): # Providing some `T` on `__init__`
self._value = value # defines the class' `T`
这允许将子类声明为泛型或具体的。
class Class1(BaseClass[str]): # "is a" BaseClass where `T = str`
pass # No need to repeat ``__init__``
class ClassT(BaseClass[T]): # "is a" BaseClass where `T = T'`
@property
def value(self) -> T:
return self._value
reveal_type(Class1("Hello World")._value) # Revealed type is 'builtins.str*'
reveal_type(Class1(b"Uh Oh!")._value) # error: Argument 1 to "Class1" has incompatible type "bytes"; expected "str"
reveal_type(ClassT(42).value) # Revealed type is 'builtins.int*'
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句