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())
的情况下判断它是否是字符串、整型、浮点型、布尔型
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?")