假设一个包含值和名称的泛型类Test
:
T = TypeVar("T", str, int, float, bool)
class Test(Generic[T]):
def __init__(self, name: str, value: T):
self._name: str = name
self._value: T = value
self._type: type = T
def set(self, new: T) -> None:
self._value = new
def get(self) -> T:
return self._value
def get_type(self) -> type:
return self._type
上面没有做我想要的 - 你可以.set
任何类型作为新值,而不仅仅是初始类型T
创建对象时。我也不知道如何提取类型T
- 如何在不调用type(test_object.get())
的情况下判断它是否是 str、int、float、bool ?
bool_var = Test("test", True)
# none of the below works the way I would have hoped:
bool_var.set("str is not a bool")
print("How do I raise an exception on the above line using Generic types?")
# I could store the type and compare it as part of the Test.set function, but is there a way
# to leverage Generics to accomplish this?
print(type(bool_var))
print(bool_var.get_type())
print("where is the value for T at the time the object was created?")
# how do I extract bool from this mess programmatically, to at least see what T was when the object was created?
我希望做的事情在 Python 中还不受支持吗?我是否以错误的方式接近泛型?
类型根本没有运行时强制,此时,它们对开发人员的提示比任何东西都重要(或由autodoc工具使用(
x:bool = input("anything as a string:")
但是,您的 IDE 可能会警告您