You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python类型检查拒绝使用父类型的子类重写属性的问题求助

Python类型检查拒绝使用父类型的子类重写属性的问题求助

我最近写Python代码时碰到了一个类型检查的问题,实在摸不着头脑,想请教下大家!

先给大家看看我的代码示例:

class Foo:
    pass

class FooChild(Foo):
    pass

class Bar:
    def __init__(self):
        self.prop: Foo

class BarChild(Bar):
    def __init__(self):
        self.prop: FooChild = FooChild()

在重写prop这个属性的时候,我的类型检查工具抛出了这样的警告:

"prop" overrides symbol of same name in class "Bar"
Variable is mutable so its type is invariant
Override type "FooChild" is not the same as base type "Foo"

我现在特别困惑,FooChild本来就是Foo的子类,按道理子类是可以兼容父类类型的啊,为啥这种场景下就不让我重写这个属性呢?

备注:内容来源于stack exchange,提问作者dododingo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 16:58:08