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

如何为基类中返回子类定义类实例的方法添加正确类型提示?

子类嵌套类的方法返回类型提示问题

假设有一个基类BaseA,其方法get_b返回类B的实例。类B同时在BaseA和继承自BaseA的子类Child中定义:

class BaseA:
    def get_b(self):
        return self.B()
    
    class B:
        pass


class Child(BaseA):
    class B(BaseA.B):
        def hello(self):
            return "hello"


Child().get_b().hello()

运行时,调用Child实例的get_b方法会返回Child中定义的B实例,代码可正常执行,但Pyright提示get_b的返回类型为BaseA.B,子类B的扩展方法无法被识别。

Pyright报错信息:

Diagnostics:
1. Cannot access attribute "hello" for class "B"
     Attribute "hello" is unknown [reportAttributeAccessIssue]

请问有没有办法为该方法添加正确的类型提示?


解决方案

可以通过**泛型(Generics)**结合Self类型来实现准确的类型提示,让类型检查器能够识别子类中重定义的嵌套类B。

方法1:使用Self类型(Python 3.11+)

Python 3.11引入的Self类型可以直接标注返回值,让类型检查器明确返回的是当前实例所属类的嵌套B类:

from typing import Self

class BaseA:
    def get_b(self) -> Self.B:
        return self.B()
    
    class B:
        pass


class Child(BaseA):
    class B(BaseA.B):
        def hello(self) -> str:
            return "hello"


Child().get_b().hello()  # 不再触发类型报错

方法2:泛型兼容旧版本(Python <3.11)

如果使用低于3.11的Python版本,可通过TypeVar和Generic定义泛型基类,关联当前类的嵌套B类型:

from typing import TypeVar, Generic

T_B = TypeVar("T_B", bound="BaseA.B")
T_Self = TypeVar("T_Self", bound="BaseA")

class BaseA(Generic[T_Self, T_B]):
    def get_b(self) -> T_B:
        return self.B()
    
    class B:
        pass


class Child(BaseA["Child", "Child.B"]):
    class B(BaseA.B):
        def hello(self) -> str:
            return "hello"


Child().get_b().hello()  # 类型检查正常通过

方法3:绑定嵌套类型的简洁泛型写法

直接用TypeVar绑定基类的嵌套B类型,写法更简洁:

from typing import TypeVar

class BaseA:
    BType = TypeVar("BType", bound="BaseA.B")
    
    def get_b(self) -> BType:
        return self.B()
    
    class B:
        pass


class Child(BaseA):
    class B(BaseA.B):
        def hello(self) -> str:
            return "hello"


Child().get_b().hello()  # Pyright可正确识别hello方法

这些方法的核心都是让类型检查器理解:get_b返回的是当前实例所属类中定义的嵌套B类,而非基类的BaseA.B。

内容的提问来源于stack exchange,提问作者squgeim

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 18:42:47