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

为何为集合变量添加NamedTuple类型注解后mypy无法识别其属性?

错误原因

你用Set[NamedTuple]作为students的类型注解时,mypy会将集合内的元素视为通用的NamedTuple抽象类型,而不是你定义的具体Student类型。NamedTuple本身没有name这个属性,所以mypy会报错提示找不到该属性。

去掉注解后,mypy会自动进行类型推断,能识别出元素是Student实例,自然不会报错。

保留类型注解的解决方法

方法1:改用typing.NamedTuple定义类型(推荐)

用typing.NamedTuple定义自定义类型,mypy能明确识别该类型的所有属性:

from typing import Set, NamedTuple

class Student(NamedTuple):
    name: str
    english: int
    math: int

students: Set[Student] = {Student('John', 100, 80),
                          Student('Mary', 90, 90),}
for student in students:
    print(student.name)

方法2:为collections.namedtuple指定具体类型注解

如果坚持使用collections.namedtuple,只需将类型注解改为具体的Student类型,而非通用的NamedTuple:

from typing import Set
from collections import namedtuple

Student = namedtuple('Student', 'name english math')
# 关键:用Set[Student]替代Set[NamedTuple]
students: Set[Student] = {Student('John', 100, 80),
                          Student('Mary', 90, 90),}
for student in students:
    print(student.name)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 17:15:37