Python访问类实例属性报错:AttributeError: class chainlist has no attribute 'chain'
AttributeError: class chainlist has no attribute 'chain' 原因分析与解决办法
咱们先拆解这个错误的根源,代码里其实有两个关键问题:
1. 构造函数定义错误
你把类的构造函数写成了___init__(前后三个下划线),但Python里标准的类构造函数是__init__(前后各两个下划线)。这就导致创建blockchain = chainlist()实例时,构造函数根本没被执行,self.chain自然也没被初始化——不过就算构造函数写对了,还有第二个问题。
2. 属性访问对象搞错了
最后一行你写的是print(chainlist.chain),这里的chainlist是类本身,但chain是你在构造函数里给实例对象(也就是blockchain)定义的属性。类本身并没有chain这个属性,只有实例才有,直接访问类的chain自然会触发AttributeError。
修复后的完整代码
class chainlist: def __init__(self): # 修正构造函数的下划线数量 self.chain = [6, 7] self.create_block(proof=1) # 补充create_block方法避免新报错,可根据需求扩展逻辑 def create_block(self, proof): pass blockchain = chainlist() print(blockchain.chain) # 访问实例的chain属性,而非类的属性
运行这段代码就能正常输出[6, 7]了。
内容的提问来源于stack exchange,提问作者m.d venkatesh
相关产品推荐
相关产品推荐

