gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 06:42:54 31 4
gpt4 key购买 nike

假设一个泛型类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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com