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

Python链表set_value方法报错:int对象无'value'属性的解决问询

问题分析与修复

错误原因

触发int object has no attribute 'value'错误的核心问题在get方法:

  • get方法里的return temp.value写在了for循环的缩进块内,导致第一次循环就直接返回节点的值(整数类型),而非节点对象本身。
  • 后续set_value拿到这个整数后,试图访问它的value属性,自然会触发整数无该属性的错误。
  • 同时,错误的return位置还会导致get无法正确遍历到指定索引的节点(比如索引1的节点永远拿不到)。

另外还有一个次要问题:最后调用打印链表的语句应为my_LL.print_list(),而非直接print_list(),否则会触发函数未定义错误。

修复后的完整代码

class Node:
    # 创建节点
    def __init__(self, value):
        self.value = value
        self.next = None 

class LinkedList : 
    def __init__(self, value):
        new_node = Node(value)
        self.head = new_node
        self.tail = new_node
        self.length = 1
    
    def print_list(self) : 
        temp = self.head
        while temp is not None :
            print(temp.value)
            temp = temp.next 

    def append(self, value): 
        new_node = Node(value) 
        if self.head is None : 
            self.head = new_node
            self.tail = new_node
        else :
            self.tail.next = new_node 
            self.tail = new_node
        self.length += 1 

    def get(self, index): 
        if index < 0 or index >= self.length :
            return None 
        temp = self.head
        for _ in range(index) :   
            temp = temp.next 
        # 移出循环,返回节点对象而非值
        return temp 

    def set_value(self, index, value ):
        temp = self.get(index)
        if temp is not None :
            temp.value = value 
            return True 
        return False 

my_LL = LinkedList(11)
my_LL.append(3)
my_LL.append(23)
my_LL.append(7)
my_LL.set_value(1,4)
# 修正调用方式
my_LL.print_list()

关键修复点说明

  • 调整get方法:将return temp.value移出for循环,改为返回temp(节点对象),这样set_value就能拿到节点对象,正常修改其value属性。
  • 修正打印链表的调用:使用my_LL.print_list()调用实例方法。

验证结果

运行修复后的代码,输出为:

11
4
23
7

符合预期,链表中索引1的节点值已从3修改为4。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 12:01:11