【问题标题】:What is the correct type hint for a class pointer? [duplicate]类指针的正确类型提示是什么? [复制]
【发布时间】:2021-10-08 18:02:12
【问题描述】:

我不确定 类指针 是否是 python 中的正确术语,但我正在这个简约示例中寻找适当的类型提示:

class AnotherClass:
    some_var=5

class SomeClass:
    def some_function(self, model: AnotherClass) -> AnotherClass:
        return model()

当我用 mypy 对上面的 sn-p 进行 typecheck 时,会抛出以下错误:

some_dir/some_file.py:6: 错误:“AnotherClass”不可调用

所以:在这种情况下,模型参数的适当类型提示是什么?


以下删除了mypy错误,但似乎不对..

def some_function(self, model: Callable[..., AnotherClass]) -> AnotherClass:
    return model()

【问题讨论】:

  • Callable[..., AnotherClass] 如果只想构造类,其实比Type[AnotherClass] 更好的解决方案。在您的情况下,您甚至会想要 Callable[[], AnotherClass],因为您希望 __init__ 不接受任何参数。
  • @MarioIshac 你能详细说明一下吗?为什么更好?引用的问题不包括此解决方案。
  • Callable[..., AnotherClass]Type[AnotherClass] 是同等(非)类型安全的,因为两者都允许传递违反 __init__ 签名的参数。前者故意抛弃类型安全(使用...),后者允许具有与AnotherClass 不同的__init__ 签名的子类。 Callable[[], AnotherClass] 是唯一的类型安全选项,因为它只允许 AnotherClass 或其子类在 __init__ 中具有 0 个参数(不包括 self)。
  • 见这个:mypy-play.net/…。只有take_3mypy 捕获(因为它是最安全的),尽管所有三个在运行时都失败了,因为没有a 被传递给SubAnotherClass__init__

标签: python mypy


【解决方案1】:

我相信您想要Type[AnotherClass],因为您传递的是类本身,而不是该类的实例。

用 C 注释的变量可以接受 C 类型的值。相反,用 Type[C] 注释的变量可以接受本身就是类的值 - 具体来说,它将接受 C 的类对象。

【讨论】:

  • 是的,这似乎是正确的 :) 谢谢!
猜你喜欢
  • 1970-01-01
  • 2021-04-08
  • 2011-03-28
  • 2016-09-25
  • 2023-04-02
  • 2017-12-29
  • 2012-02-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多