Код: Выделить всё
from typing import Any, Callable, Generic, Self, TypeVar
_R = TypeVar('_R')
class classproperty(Generic[_R]):
def __init__(self, method: Callable[..., _R]):
self.fget = method
def __get__(self, _instance: Any, cls: Any) -> _R:
return self.fget(cls)
_T = TypeVar('_T')
class Demo(Generic[_T]):
def __init__(self, inner: _T):
self._inner = inner
@property
def child_self(self) -> _T:
return self._inner
class Base:
@classproperty
def query(cls) -> Demo[Self]:
return Demo(cls()) # type: ignore
@classmethod
def query_method(cls) -> Demo[Self]:
return Demo(cls()) # type: ignore
class A(Base):
id = 1
# eventhing is ok
print(A.query_method().child_self.id)
# mypy error: "Self" has no attribute "id" [attr-defined]
print(A.query.child_self.id)
Python: 3.12.1
Как правильно добавлять подсказки типов, исправлена ошибка mypy. Или любое другое свойство класса синтаксиса. Невозможно изменить Base.query, этот синтаксис используется слишком во многих местах.
Подробнее здесь: https://stackoverflow.com/questions/792 ... -with-mypy