问题中描述的方法似乎适用于 Mypy 和 PyCharm 类型检查器。
编辑:显然我的示例代码类型检查,但 MyPy 实际上无法推断版本 0.800 的类型。
"""Defines the `classproperty` decorator."""
from typing import Any, Callable, Optional, Type, TypeVar
T = TypeVar("T")
V = TypeVar("V")
class classproperty(property):
"""Class property decorator."""
def __init__(self, getter: Callable[[Any], V]) -> None:
"""Override getter."""
self.getter = getter # type: ignore
def __get__(self, instance: Optional[T], owner: Type[T]) -> V: # type: ignore
return self.getter(owner) # type: ignore
def __set__(self, obj, value):
super(classproperty, self).__set__(type(obj), value)
def __delete__(self, obj):
super(classproperty, self).__delete__(type(obj))
class Thing:
@classproperty
def value1(cls) -> int:
return 44
value2 = classproperty(lambda cls: 55)
@property
def value3(self) -> int:
return 66
thing = Thing()
reveal_type(thing.value1)
reveal_type(thing.value2)
reveal_type(thing.value3)
main.py:40: note: Revealed type is '<nothing>'
main.py:41: note: Revealed type is '<nothing>'
main.py:42: note: Revealed type is 'builtins.int'
https://mypy-play.net/?mypy=0.800&python=3.9&gist=79f6fab466ecc4c4b45b75f1c7b6a6a8。