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

如何在Python中创建指定自定义类类型的空列表并添加类型注解

为存储自定义类实例的空列表添加类型注解的正确方法

我是Python新手,希望通过为变量添加类型注解提前发现错误,同时获得IDE的更好支持。我需要创建一个存储自定义myClass实例的空列表并为其指定类型。现有可运行代码能创建列表但未添加类型注解,尝试将列表赋值为None、赋值为myClass实例均触发异常,寻求正确实现方法。

可运行代码(无类型注解)

class myClass:
    def __init__(self,sample,text):
        self.sample = sample
        self.text = text
        
arr = []# 我必须先初始化空列表,因为后续会在for循环中添加数据

arr.append(myClass("hello1","world2"))
arr.append(myClass("hello1","world2"))

for item in arr:
    print(item.sample + " " + item.text)

错误尝试及问题

错误尝试1

arr2: list[myClass] = None
arr2.append(myClass("hello3","world3"))
arr2.append(myClass("hello4","world4"))
for item in arr2:
    print(item.sample + " " + item.text)

异常:'NoneType' object has no attribute 'append'
原因:将变量赋值为None,但None不是列表类型,无法调用append方法。

错误尝试2

arr3: list[myClass] = myClass(None,None)
arr3.append(myClass())
arr3.append(myClass("hello5","world5"))
arr3.append(myClass("hello6","world6"))
for item in arr3:
    print(arr3[item].sample + " " + arr3[item].text)

异常:'myClass' object has no attribute 'append'
原因:将变量赋值为myClass的实例,而不是列表,实例没有append方法。

正确实现方法

类型注解的作用是标注变量的预期类型,但变量的实际值必须符合该类型。要创建存储myClass实例的空列表并添加类型注解,只需在初始化空列表时加上类型标注即可:

class myClass:
    def __init__(self,sample,text):
        self.sample = sample
        self.text = text
        
# 正确:标注类型为list[myClass],同时初始化为空列表
arr: list[myClass] = []

arr.append(myClass("hello1","world2"))
arr.append(myClass("hello1","world2"))

for item in arr:
    print(item.sample + " " + item.text)

这样既完成了类型注解,保证IDE能提供正确的代码提示和类型检查,同时变量的实际值是空列表,后续可以正常调用append方法添加myClass实例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 04:15:40