gpt4 book ai didi

python - 输入 : How to bind owner class to generic descriptor?

转载 作者:行者123 更新时间:2023-12-03 14:21:29 25 4
gpt4 key购买 nike

我可以在 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"

关于python - 输入 : How to bind owner class to generic descriptor?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64622708/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com