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

如何查看namedtuple的名称?遍历namedtuple列表时判断元素类型

关于namedtuple的两个问题解答

问题1:如何查看namedtuple的名称?

你可以通过两种方式获取namedtuple的名称:

  • 访问实例的__typename__属性:直接从namedtuple对象上读取该属性,返回定义时指定的名称。
  • 访问类的__name__属性:通过type(实例).__name__获取该namedtuple类的名称。

示例代码:

from collections import namedtuple

Student = namedtuple('Student', ['ID', 'name'])
s = Student(ID='1', name='abc')

# 方法1:用__typename__
print(s.__typename__)  # 输出: Student

# 方法2:用type()和__name__
print(type(s).__name__)  # 输出: Student

问题2:遍历namedtuple列表时,如何判断元素类型是Student还是Room?

有两种常用的判断方式:

  • 使用isinstance()函数:这是Python中判断对象类型的标准方法,直接检查元素是否属于目标namedtuple类。
  • 对比__typename__属性:通过元素的__typename__值与目标名称对比来判断类型。

示例代码:

from collections import namedtuple

Student = namedtuple('Student', ['ID', 'name'])
Room = namedtuple('Room', ['number', 'location'])

obj_list = [
    Student(ID='1', name='abc'),
    Room(number='1', location='4th floor'),
    Student(ID='2', name='xyz')
]

# 方法1:用isinstance()
for item in obj_list:
    if isinstance(item, Student):
        print(f"这是Student类型: {item}")
    elif isinstance(item, Room):
        print(f"这是Room类型: {item}")

# 方法2:用__typename__属性
for item in obj_list:
    if item.__typename__ == 'Student':
        print(f"这是Student类型: {item}")
    elif item.__typename__ == 'Room':
        print(f"这是Room类型: {item}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 20:55:31