【问题标题】:Type-hinting classes belonging to the same interface属于同一接口的类型提示类
【发布时间】:2021-11-17 22:47:22
【问题描述】:

代码:

import abc


class Interface(abc.ABC):
    @abc.abstractmethod
    @classmethod
    def make(cls): ...

class AObject(Interface):
    def __init__(self, a: int):
        self.a = a

    @classmethod
    def make(cls):
        return cls(a=3)

class BObject(Interface):
    def __init__(self, b: int):
        self.b = b

    @classmethod
    def make(cls):
        return cls(b=3)


data: tuple[Interface, ...] = (AObject, BObject) # Incompatible types in assignment (expression has type "Tuple[Type[AObject], Type[BObject]]", variable has type "Tuple[Interface, ...]")  [assignment]

有一个实现类的接口,我们需要指定该类存在类方法make。但是如果你指定了tuple[Interface, ...]的类型,MyPy会返回一个错误,因为你只能为类实例指定类型,不能为类本身指定类型

那么,问题是——如何正确地做到这一点?

【问题讨论】:

    标签: python type-hinting mypy python-typing


    【解决方案1】:

    我不确定我是否理解你的问题,但如果你想指定一个变量存储某种类,你可以使用typing.Type

    import abc
    from typing import Tuple, Type
    ...
    data: Tuple[Type[Interface], Type[Interface]] = (AObject, BObject)  # mypy is happy
    

    【讨论】:

    • 而在python >=3.9中,可以直接参数化内置的type函数。
    猜你喜欢
    • 1970-01-01
    • 2011-03-14
    • 1970-01-01
    • 2014-09-10
    • 2021-05-11
    • 2019-11-11
    • 2021-05-16
    • 2022-12-19
    • 1970-01-01
    相关资源
    最近更新 更多