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

VSCode中用Python泛型时Pylance报‘Object of type 'A*' is not callable’错误的原因与解决

问题分析与解决

错误原因解析

错误1:self.processors: List[T] = []

你定义的T = TypeVar("T", A, B)是实例类型(代表A或B的对象实例),但在__init__方法中,你传入的是类(比如B),却把参数processor标注为T(实例类型),这导致泛型绑定逻辑混乱。Pylance无法正确识别T的实际类型,因此抛出“Variable not allowed in type expression”错误。

错误2:proc: T = self.processor_class()

由于processor参数被错误标注为实例类型T,Pylance认为self.processor_class是A/B的实例对象,而不是类。实例对象无法通过()调用(只有类或可调用对象可以),因此抛出“Object of type 'A*' is not callable”错误。

解决方法

核心是区分类类型和实例类型:

  1. 导入Type用于标注类类型;
  2. 调整泛型参数,明确T代表A/B的实例类型,__init__接收的是Type[T](即A或B的类本身);
  3. 修正所有类型标注,让类型系统正确识别类和实例的关系。

修正后的代码

from typing import List, TypeVar, Generic, Type

class A:
    def __init__(self):
        pass

    def process(self, x: int) -> int:
        return x + 1

class B:
    def __init__(self):
        pass

    def process(self, x: int) -> int:
        return x + 2

# T代表A或B的实例类型
T = TypeVar("T", A, B)

class ListProcessor(Generic[T]):
    """Apply a Transformer to the individual list elements."""

    # processor参数接收的是A或B的类,用Type[T]标注
    def __init__(self, processor: Type[T]):
        self.processor_class = processor
        # processors存储的是T的实例,类型标注正确
        self.processors: List[T] = []

    # 明确输入X的类型和返回值类型
    def process(self, X: List[int]) -> List[int]:
        x_processed = []
        for x in X:
            # processor_class是类,调用后得到T的实例,类型匹配
            proc: T = self.processor_class()
            result = proc.process(x)
            x_processed.append(result)
            self.processors.append(proc)
        return x_processed

lp = ListProcessor(B)
print(lp.process([1, 2, 3]))  # 输出: [3,4,5]

关键修改点

  • 新增导入Type,用于标注类类型;
  • __init__的processor参数标注为Type[T],明确接收的是类而非实例;
  • 给A和B的process方法补充了输入输出的类型标注,增强类型检查的准确性;
  • process方法明确了输入X的类型为List[int],返回值为List[int],避免模糊的List类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 21:44:54