如何解决类型:如何将所有者类绑定到通用描述符?
我可以用Python支持/尊重/理解其所有者的继承体系的方式来实现通用描述符吗?
代码中应该更清楚:
from typing import (
Generic,Optional,TYPE_CHECKING,Type,TypeVar,Union,overload,)
T = TypeVar("T",bound="A") # noqa
class Descr(Generic[T]):
@overload
def __get__(self: "Descr[T]",instance: None,owner: Type[T]) -> "Descr[T]": ...
@overload
def __get__(self: "Descr[T]",instance: T,owner: Type[T]) -> T: ...
def __get__(self: "Descr[T]",instance: Optional[T],owner: Type[T]) -> Union["Descr[T]",T]:
if instance is None:
return self
return instance
class A:
attr: int = 123
descr = Descr[T]() # I want to bind T here,but don't know how
class B(A):
new_attr: int = 123
qwerty: str = "qwe"
if __name__ == "__main__":
a = A()
if TYPE_CHECKING:
reveal_type(a.descr) # mypy guess it is T? but I want A*
print("a.attr =",a.descr.attr) # mypy error: T? has no attribute "attr"
# no runtime error
b = B()
if TYPE_CHECKING:
reveal_type(b.descr) # mypy said it's T? but I want B*
print("b.new_attr =",b.descr.new_attr) # mypy error: T? has no attribute "new_attr"
# no runtime error
print("b.qwerty =",b.descr.qwerty) # mypy error: T? has no attribute "qwerty"
# (no runtime error)
gist-要点上几乎相同的代码段
解决方法
我不确定您是否需要将描述符类设为通用类;将__get__
的实例上的Type[T]
返回T
可能就足够了:
T = TypeVar("T") # noqa
class Descr:
@overload
def __get__(self,instance: None,owner: Type[T]) -> "Descr": ...
@overload
def __get__(self,instance: T,owner: Type[T]) -> T: ...
def __get__(self,instance: Optional[T],owner: Type[T]) -> Union["Descr",T]:
if instance is None:
return self
return instance
class A:
attr: int = 123
descr = Descr()
class B(A):
new_attr: int = 123
qwerty: str = "qwe"
您的每个示例都能按您的意愿工作,并且将会出现错误
print("b.spam =",b.descr.spam)
产生
error: "B" has no attribute "spam"
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。