假设有一个包含值和名称的泛型类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())
的情况下判断它是否是字符串、整型、浮点型、布尔型
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还不支持我希望做的事情吗?我处理泛型的方式是错误的吗?
发布于 2019-12-17 12:25:33
类型没有运行时强制,目前,它们更多地是对开发人员的一种暗示(或由autodoc工具使用)。
x:bool = input("anything as a string:")
但是,您的ide可能会警告您。
https://stackoverflow.com/questions/59367566
复制相似问题