python - 正确使用 Python 泛型 - 如何获取泛型 var 的类型并在初始化后在对象内强制执行一致的类型?

标签 python python-3.x generics types python-3.8

假设一个泛型类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被 build 。我也无法弄清楚如何提取类型 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可能会警告你

关于python - 正确使用 Python 泛型 - 如何获取泛型 var 的类型并在初始化后在对象内强制执行一致的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59367566/

相关文章:

Java 泛型和 addAll 方法

c - 是否可以实现一个可以在 C 中打印任何类型的任何数组的函数?

python - Selenium - 我对服务器的访问量有多大?

python - 如果没有 python 中的所有样板,从 QUiLoader 加载是否安全?

python-3.x - 比较两个数据帧并根据匹配的列值从 df 中删除行

python - 什么是引用窃取和借用?

c# - 作为泛型类型传递的访问类属性

python - numpy - 用 0 调整数组大小

python - 如何继承 defaultdict 并在子类方法中使用它的复制方法?

python-3.x - Python-OpenCV cv2 OpenCV错误: Assertion failed