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

Python类方法创建对象时类型标注失效问题求助

泛型类方法创建实例的类型标注修复方案

问题代码

from typing import Generic, TypeVar, Union

T = TypeVar('T')

class Bar(object):
    def __init__(self, blah: Union[int, str]) -> None:
        self.blah = blah

class Foo(Generic[T]):

    def __init__(self, bar: T) -> None:
        self.bar = bar

    @classmethod
    def extract(cls, klass: T) -> 'Foo':
        return cls(bar=klass(123))

foo = Foo.extract(Bar)
foo.bar # 类型检查器识别为Any

foo1 = Foo(Bar(123))
foo1.bar # 类型检查器正确识别为Bar

问题描述

使用VSCode最新版Pylance和Python扩展时,通过Foo.extract(Bar)创建的实例,其bar属性被识别为Any;但直接通过Foo(Bar(123))实例化的对象,bar属性能正确识别为Bar类型。需要让类方法创建的对象拥有正确的类型标注。

原因与修复

问题出在类方法extract的类型标注错误:

  • 原代码中klass: T的标注不符合实际传入的类型:T是Foo泛型对应的实例类型(比如Bar的实例),但实际传入的是Bar类本身,类型应为Type[T]。
  • 返回类型仅标注为Foo,未明确泛型参数T,导致类型检查器无法推断具体类型。

修改后的代码:

from typing import Generic, TypeVar, Union, Type

T = TypeVar('T')

class Bar(object):
    def __init__(self, blah: Union[int, str]) -> None:
        self.blah = blah

class Foo(Generic[T]):
    def __init__(self, bar: T) -> None:
        self.bar = bar

    @classmethod
    def extract(cls, klass: Type[T]) -> 'Foo[T]':
        return cls(bar=klass(123))

foo = Foo.extract(Bar)
foo.bar # 现在类型检查器正确识别为Bar

修改点说明:

  1. 导入Type用于标注类类型;
  2. 将extract方法的参数klass标注为Type[T],明确传入的是能生成T类型实例的类;
  3. 返回类型明确标注为Foo[T],让类型检查器关联泛型参数,从而正确推断bar的类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 11:45:45