1 回答
![?](http://img1.sycdn.imooc.com/545863e80001889e02200220-100-100.jpg)
TA贡献1874条经验 获得超12个赞
要解决这个问题,只需键入您的get_self函数,def get_self(self: S) -> S其中 S 是某种类型 var。
然后,以下程序将干净地键入检查:
from __future__ import annotations
from typing import Generic, TypeVar, cast
T = TypeVar("T")
# This can also be just 'S = TypeVar("S")', but that would mean
# we won't be able to use any methods of Foo inside of get_self.
S = TypeVar("S", bound="Foo")
class Foo(Generic[T]):
def get_self(self: S) -> S:
return self
class Bar:
pass
class DFoo(Foo[Bar]):
def do_something_get_self(self) -> DFoo:
return self.get_self()
def dfoo_adds_method(self) -> None:
pass
dfoo = DFoo()
dfoo.do_something_get_self().dfoo_adds_method()
这样做的原因是因为它总是可以覆盖self. 虽然它通常会自动给出当前类的类型,但 PEP 484 实际上并不要求您坚持使用此默认值。
因此,我们将其设为通用,以确保输出类型始终与当前子类型匹配。
添加回答
举报