属于同一接口的类型提示 类

Type-hinting classes belonging to the same interface

代码:

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]

有一个实现 classes 的接口,我们需要指定 class 方法 make 存在于 class。但是,如果您指定类型 tuple[Interface, ...],MyPy 将 return 出错,因为您只能为 class 个实例指定类型,而不能为 classes 本身指定类型

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

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

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