正确使用Python泛型-如何在初始化后如何获取泛型var的类型并在对象内一致地实施该类型?

问题描述 投票:0回答:1

假定具有值和名称的通用类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?我是否以错误的方式接近泛型?

python python-3.x generics types python-3.8
1个回答
0
投票

类型完全没有运行时强制,目前,它们对开发人员的提示比其他任何东西(或自动文档工具所使用的都多)

x:bool = input("anything as a string:")

但是您的想法可能会警告您

© www.soinside.com 2019 - 2024. All rights reserved.