首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >正确使用Python泛型-如何获得泛型变量的类型,并在初始化后一致地在对象中强制执行该类型?

正确使用Python泛型-如何获得泛型变量的类型,并在初始化后一致地在对象中强制执行该类型?
EN

Stack Overflow用户
提问于 2019-12-17 12:17:00
回答 1查看 521关注 0票数 1

假设有一个包含值和名称的泛型类Test

代码语言:javascript
复制
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())的情况下判断它是否是字符串、整型、浮点型、布尔型

代码语言:javascript
复制
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还不支持我希望做的事情吗?我处理泛型的方式是错误的吗?

EN

回答 1

Stack Overflow用户

发布于 2019-12-17 12:25:33

类型没有运行时强制,目前,它们更多地是对开发人员的一种暗示(或由autodoc工具使用)。

代码语言:javascript
复制
x:bool = input("anything as a string:")

但是,您的ide可能会警告您。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59367566

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档