【问题标题】:mypy TypeVar include bound class as well as subclassesmypy TypeVar 包括绑定类以及子类
【发布时间】:2021-05-18 10:54:04
【问题描述】:
class Super:
    @classmethod
    def instantiate(cls) -> What goes here?:
        return cls()

class Sub(Super):
    pass

class Sub2(Super):
    pass

在编写类型提示时,说方法应该返回超类或其任何子类的实例的规范方式是什么。我能找到的最接近的是TypeVar("Super", bound="Super"),但这仍然会引发 mypy 中的 Super 类的错误

【问题讨论】:

    标签: static mypy


    【解决方案1】:

    您可以在这里使用typing.Type 来输入提示cls,如下所示:

    from typing import TypeVar, Type
    
    C = TypeVar("C")
    
    class Super:
        @classmethod
        def instantiate(cls: Type[C]) -> C:
            return cls()
    
    class Sub(Super):
        pass
    
    class Sub2(Super):
        pass
    
    reveal_type(Sub.instantiate()) # note: Revealed type is 'tmp.Sub*'
    reveal_type(Sub2.instantiate()) # note: Revealed type is 'tmp.Sub2*'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-29
      • 2020-01-24
      • 2015-07-19
      • 1970-01-01
      • 2021-10-24
      • 2020-08-03
      • 1970-01-01
      相关资源
      最近更新 更多