python - 如何在Python中使用变量的值作为类型提示

标签 python oop python-typing code-completion

如何将变量值指定为类型提示?我附上了我想要实现的示例代码:

class Class1:
    var1 = 1

class Class2:
    var2 = 2

class BaseClass:
    def __init__(self, var):
        self.var = var

class ChildClass1(BaseClass):
    def __init__(self):
        super().__init__(var=Class1)

    def fun(self):
        self.var.  # How to get type hint here for Class1 like it should show var1

class ChildClass2(BaseClass):
    def __init__(self):
        super().__init__(var=Class2)

    def fun(self):
        self.var.  # How to get type hint here for Class2 like it should show var2

编辑 1:“类型提示”是指在输入 self.var 后,IDE 的智能感知应该给出我的建议,就像我们输入 str() 时得到的建议一样。 然后我们得到例如strip().

编辑2:@DaniilFajnberg 为问题提供了一个很好的解决方案,即泛型,但仍然保持问题活跃,因为我正在寻找泛型以外的解决方案(我已经在评论中提到过)。

最佳答案

我知道您在评论中特别提到您想要泛型,但由于它们这个问题的教科书解决方案,也许其他人遇到过这个问题会发现这很有用:

from typing import Generic, TypeVar

T = TypeVar("T")

class Class1:
    var1 = 1

class Class2:
    var2 = 2

class BaseClass(Generic[T]):
    var: type[T]

    def __init__(self, var: type[T]) -> None:
        self.var = var

class ChildClass1(BaseClass[Class1]):
    def __init__(self) -> None:
        super().__init__(var=Class1)

class ChildClass2(BaseClass[Class2]):
    def __init__(self) -> None:
        super().__init__(var=Class2)

if __name__ == '__main__':
    child1 = ChildClass1()
    child2 = ChildClass2()
    reveal_type(child1.var)  # this line is for mypy
    reveal_type(child2.var)  # this line is for mypy

这会导致 mypy 给出以下输出:

[...].py:35: note: Revealed type is "Type[[...].Class1]"
[...].py:36: note: Revealed type is "Type[[...].Class2]"

任何有值(value)的 IDE 都会通过此设置为您提供所需的自动建议。

请记住,运行时类型注释是一个矛盾的术语。

关于python - 如何在Python中使用变量的值作为类型提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74129786/

相关文章:

python - 提取给定数组中的公共(public)元素以生成新数组

python - Python 线程什么时候快?

oop - 代码中的顺序耦合

php - fatal error : Call to a member function query() PHP CLASS

python - 如何用 python-attrs 构造解决 "unexpected keyword argument",让 mypy 开心?

python - 模型属性是否有 Pydantic 约定,默认为另一个属性的函数?

python - 联合集或检查整个列表是否重复更快?

python - Networkx 复制说明

swift - 为什么 'self.self'在swift中编译运行?

Python void 返回类型注解