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

Python报错:'Foo' object has no attribute 'myList',求解决方案

问题解决:'Foo' object has no attribute 'myList'

这是Python大小写敏感特性导致的拼写错误:你在__init__方法中给实例绑定的属性是小写的self.mylist,但在myIter方法里尝试访问的是大写开头的self.myList,两者被Python识别为完全不同的属性,因此报错。

只需要保持两处属性名称的拼写(包括大小写)一致即可解决问题,以下是两种修正方案:

方案一:统一使用小写mylist

class Foo:
   
    def __init__(self, mylist):
        self.mylist = mylist
    
    def myIter(self):
        for i in self.mylist:
            print(i)
            
first = [1,2,4,3,5,6]
f = Foo(first)
f.myIter()

方案二:统一使用大写开头的myList

class Foo:
   
    def __init__(self, mylist):
        self.myList = mylist
    
    def myIter(self):
        for i in self.myList:
            print(i)
            
first = [1,2,4,3,5,6]
f = Foo(first)
f.myIter()

运行修正后的代码,就能正常遍历列表并打印元素了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 13:35:40