我有如下内容:
from typing import TypeVar, Callable, Generic, Type, Union, Optional
T = TypeVar("T")
V = TypeVar("V")
class DescClass(Generic[T, V]):
"""A descriptor."""
def __init__(self, func: Callable[[T], V]) -> None:
self.func = func
def __get__(self, instance: Optional[T], owner: Type[T]) -> Callable[[], V]:
return self.func.__get__(instance, owner)
class C:
@DescClass
def f(self): ...
... Mypy将为此返回错误:
test.py:12: error: "Callable[[T], Any]" has no attribute "__get__"
为func
指定类型的规范方法是什么,以便Mypy理解它是描述符(and thus always has a __get__
)?
更新:搜索Mypy帮助时,“描述符” has no hits有点幽默。