经过一段时间的努力解决这个问题,当您搜索“类型提示描述符”时,此页面是最重要的结果,我想分享一个完全满足 mypy 和 Pyright 静态类型检查器的解决方案,与 python 3.6 兼容并且不兼容继承自property
from typing import Callable, Generic, Type, TypeVar, overload, Union
Instance = TypeVar('Instance')
Value = TypeVar('Value')
Attribute = TypeVar('Attribute')
class Descriptor(Generic[Instance, Attribute, Value]):
def __init__(self, method: Callable[[Instance, Attribute], Value]):
""" Called on initialisation of descriptor """
@overload
def __get__(self, instance: None, owner: Type[Instance]) -> 'Descriptor':
""" Called when an attribute is accessed via class not an instance """
@overload
def __get__(self, instance: Instance, owner: Type[Instance]) -> Value:
""" Called when an attribute is accessed on an instance variable """
def __get__(self, instance: Union[Instance, None], owner: Type[Instance]) -> Union[Value, 'Descriptor']:
""" Full implementation is declared here """
...
def __set__(self, instance: Instance, value: Value):
""" Called when setting a value."""