问题是,在以下情况下,SubFoo类中的自动完成在Pylance中不起作用。Pylance只识别Bar类在SubFoo类中的方法和属性,而不识别SubBar类的方法和属性。我做的对吗?
class Bar:
def method1(self):
# do stuff
class SubBar(Bar):
def method2(self):
# do stuff
class Foo:
def __init__(self, arg: Bar):
self.attr: Bar = arg
def do_a(self):
self.attr.method1()
class SubFoo(Foo):
def __init__(self, arg: SubBar):
super().__init__(arg)
def do_b(self):
self.attr.method1() # Pylance's autocopmletion recognizes method1()
self.attr.method2() # Pylance's autocopmletion doesn't recognize method2()发布于 2022-08-30 15:28:08
您已经将Foo.attr类型声明为Bar。事实上,它碰巧在某个点被分配了一个SubBar,这不是类型检查器所关心的问题。如果您想静态地根据子类知道字段的类型,那么Foo应该是通用。
from typing import TypeVar, Generic
_T = TypeVar("_T", bound=Bar)
class Foo(Generic[_T]):
def __init__(self, arg: _T):
self.attr: _T = arg
def do_a(self):
self.attr.method1()
class SubFoo(Foo[SubBar]):
def __init__(self, arg: SubBar):
super().__init__(arg)
def do_b(self):
...现在需要Foo的子类来报告他们期望构造函数接收的Bar的哪个子类,并且这种类型的信息可以静态地使用。
如果用例支持该类型变量,您还需要考虑将其设置为协变。
https://stackoverflow.com/questions/73544765
复制相似问题