【发布时间】: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